├── .appveyor.yml ├── .codecov.yml ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .gitmodules ├── .travis.yml ├── .vscode ├── launch.json ├── settings.json ├── spell.json └── tasks.json ├── CONTRIBUTING.md ├── CONVERSION.md ├── LICENSE ├── README.md ├── antlr4ts.njsproj ├── antlr4ts.sln ├── benchmark ├── Graphemes.g4 ├── Java.g4 ├── JavaLR.g4 ├── JavaUnicodeInputStream.ts ├── Stopwatch.ts ├── TestPerformance.ts ├── TimeLexerSpeed.ts ├── TimeSpan.ts ├── emoji.txt ├── udhr_hin.txt └── udhr_kor.txt ├── package-lock.json ├── package.json ├── reference └── .editorconfig ├── src ├── ANTLRErrorListener.ts ├── ANTLRErrorStrategy.ts ├── ANTLRFileStream.tssoon ├── ANTLRInputStream.ts ├── BailErrorStrategy.ts ├── BufferedTokenStream.ts ├── CharStream.ts ├── CharStreams.ts ├── CodePointBuffer.ts ├── CodePointCharStream.ts ├── CommonToken.ts ├── CommonTokenFactory.ts ├── CommonTokenStream.ts ├── ConsoleErrorListener.ts ├── Decorators.ts ├── DefaultErrorStrategy.ts ├── Dependents.ts ├── DiagnosticErrorListener.ts ├── FailedPredicateException.ts ├── InputMismatchException.ts ├── IntStream.ts ├── InterpreterRuleContext.ts ├── Lexer.ts ├── LexerInterpreter.ts ├── LexerNoViableAltException.ts ├── ListTokenSource.ts ├── NoViableAltException.ts ├── Parser.ts ├── ParserErrorListener.ts ├── ParserInterpreter.ts ├── ParserRuleContext.ts ├── ProxyErrorListener.ts ├── ProxyParserErrorListener.ts ├── RecognitionException.ts ├── Recognizer.ts ├── RuleContext.ts ├── RuleContextWithAltNum.ts ├── RuleDependency.ts ├── RuleVersion.ts ├── Token.ts ├── TokenFactory.ts ├── TokenSource.ts ├── TokenStream.ts ├── TokenStreamRewriter.ts ├── UnbufferedCharStream.tssoon ├── UnbufferedTokenStream.tssoon ├── Vocabulary.ts ├── VocabularyImpl.ts ├── WritableToken.ts ├── atn │ ├── ATN.ts │ ├── ATNConfig.ts │ ├── ATNConfigSet.ts │ ├── ATNDeserializationOptions.ts │ ├── ATNDeserializer.ts │ ├── ATNSerializer.tssoon │ ├── ATNSimulator.ts │ ├── ATNState.ts │ ├── ATNStateType.ts │ ├── ATNType.ts │ ├── AbstractPredicateTransition.ts │ ├── ActionTransition.ts │ ├── AmbiguityInfo.ts │ ├── AtomTransition.ts │ ├── BasicBlockStartState.ts │ ├── BasicState.ts │ ├── BlockEndState.ts │ ├── BlockStartState.ts │ ├── CodePointTransitions.ts │ ├── ConflictInfo.ts │ ├── ContextSensitivityInfo.ts │ ├── DecisionEventInfo.ts │ ├── DecisionInfo.ts │ ├── DecisionState.ts │ ├── EpsilonTransition.ts │ ├── ErrorInfo.ts │ ├── InvalidState.ts │ ├── LL1Analyzer.ts │ ├── LexerATNSimulator.ts │ ├── LexerAction.ts │ ├── LexerActionExecutor.ts │ ├── LexerActionType.ts │ ├── LexerChannelAction.ts │ ├── LexerCustomAction.ts │ ├── LexerIndexedCustomAction.ts │ ├── LexerModeAction.ts │ ├── LexerMoreAction.ts │ ├── LexerPopModeAction.ts │ ├── LexerPushModeAction.ts │ ├── LexerSkipAction.ts │ ├── LexerTypeAction.ts │ ├── LookaheadEventInfo.ts │ ├── LoopEndState.ts │ ├── NotSetTransition.ts │ ├── OrderedATNConfigSet.ts │ ├── ParseInfo.ts │ ├── ParserATNSimulator.ts │ ├── PlusBlockStartState.ts │ ├── PlusLoopbackState.ts │ ├── PrecedencePredicateTransition.ts │ ├── PredicateEvalInfo.ts │ ├── PredicateTransition.ts │ ├── PredictionContext.ts │ ├── PredictionContextCache.ts │ ├── PredictionMode.ts │ ├── ProfilingATNSimulator.ts │ ├── RangeTransition.ts │ ├── RuleStartState.ts │ ├── RuleStopState.ts │ ├── RuleTransition.ts │ ├── SemanticContext.ts │ ├── SetTransition.ts │ ├── SimulatorState.ts │ ├── StarBlockStartState.ts │ ├── StarLoopEntryState.ts │ ├── StarLoopbackState.ts │ ├── TokensStartState.ts │ ├── Transition.ts │ ├── TransitionType.ts │ ├── WildcardTransition.ts │ └── index.ts ├── dfa │ ├── AcceptStateInfo.ts │ ├── DFA.ts │ ├── DFASerializer.ts │ ├── DFAState.ts │ ├── LexerDFASerializer.ts │ └── index.ts ├── index.ts ├── misc │ ├── Args.ts │ ├── Array2DHashMap.ts │ ├── Array2DHashSet.ts │ ├── ArrayEqualityComparator.ts │ ├── Arrays.ts │ ├── BitSet.ts │ ├── Character.ts │ ├── DefaultEqualityComparator.ts │ ├── DoubleKeyMap.tssoon │ ├── EqualityComparator.ts │ ├── FlexibleHashMap.tssoon │ ├── IntSet.ts │ ├── IntegerList.ts │ ├── IntegerStack.ts │ ├── InterpreterDataReader.ts │ ├── Interval.ts │ ├── IntervalSet.ts │ ├── LogManager.tssoon │ ├── MultiMap.ts │ ├── MurmurHash.ts │ ├── ObjectEqualityComparator.ts │ ├── OrderedHashSet.tssoon │ ├── ParseCancellationException.ts │ ├── RuleDependencyChecker.tssoon │ ├── RuleDependencyProcessor.tssoon │ ├── Stubs.ts │ ├── UUID.ts │ ├── Utils.ts │ ├── Utils.tssoon │ └── index.ts └── tree │ ├── AbstractParseTreeVisitor.ts │ ├── ErrorNode.ts │ ├── ParseTree.ts │ ├── ParseTreeListener.ts │ ├── ParseTreeProperty.ts │ ├── ParseTreeVisitor.ts │ ├── ParseTreeWalker.ts │ ├── RuleNode.ts │ ├── SyntaxTree.ts │ ├── TerminalNode.ts │ ├── Tree.ts │ ├── Trees.ts │ ├── index.ts │ ├── pattern │ ├── Chunk.ts │ ├── ParseTreeMatch.ts │ ├── ParseTreePattern.ts │ ├── ParseTreePatternMatcher.ts │ ├── RuleTagToken.ts │ ├── TagChunk.ts │ ├── TextChunk.ts │ ├── TokenTagToken.ts │ └── index.ts │ └── xpath │ ├── XPath.ts │ ├── XPathElement.ts │ ├── XPathLexer.g4 │ ├── XPathLexerErrorListener.ts │ ├── XPathRuleAnywhereElement.ts │ ├── XPathRuleElement.ts │ ├── XPathTokenAnywhereElement.ts │ ├── XPathTokenElement.ts │ ├── XPathWildcardAnywhereElement.ts │ ├── XPathWildcardElement.ts │ └── index.ts ├── target └── src │ ├── .npmignore │ └── package.json ├── test ├── TestArray2DHashSet.ts ├── TestBitSet.ts ├── TestMurmurHash.ts ├── TestTokenStream.ts ├── runtime │ ├── BaseTest.ts │ ├── TestGrammar.g4 │ ├── TestReferenceToListLabels │ │ ├── T.g4 │ │ └── Test.ts │ └── tsconfig.json └── tool │ ├── BaseTest.tssoon │ ├── ErrorQueue.tssoon │ ├── InterpreterTreeTextProvider.tssoon │ ├── ParseTreeMatcherX1.g4 │ ├── ParseTreeMatcherX2.g4 │ ├── ParseTreeMatcherX3.g4 │ ├── ParseTreeMatcherX4.g4 │ ├── ParseTreeMatcherX5.g4 │ ├── ParseTreeMatcherX6.g4 │ ├── ParseTreeMatcherX7.g4 │ ├── ParseTreeMatcherX8.g4 │ ├── ParserInterpreterForTesting.tssoon │ ├── RewriterLexer1.g4 │ ├── RewriterLexer2.g4 │ ├── RewriterLexer3.g4 │ ├── TestATNDeserialization.tssoon │ ├── TestATNInterpreter.tssoon │ ├── TestATNLexerInterpreter.tssoon │ ├── TestATNParserPrediction.tssoon │ ├── TestATNSerialization.tssoon │ ├── TestAmbigParseTrees.tssoon │ ├── TestBufferedTokenStream.tssoon │ ├── TestCharStreams.ts │ ├── TestCodePointCharStream.ts │ ├── TestCommonTokenStream.tssoon │ ├── TestDollarParser.tssoon │ ├── TestEscapeSequenceParsing.tssoon │ ├── TestGrammarParserInterpreter.tssoon │ ├── TestGraphNodes.ts │ ├── TestIntegerList.ts │ ├── TestIntervalSet.ts │ ├── TestLexerActions.tssoon │ ├── TestLookaheadTrees.tssoon │ ├── TestParseErrors.tssoon │ ├── TestParseTreeMatcher.ts │ ├── TestParserExec.tssoon │ ├── TestParserInterpreter.tssoon │ ├── TestParserProfiler.tssoon │ ├── TestRuleVersioning.tssoon │ ├── TestTokenStreamRewriter.ts │ ├── TestUnbufferedCharStream.tssoon │ ├── TestUnbufferedTokenStream.tssoon │ ├── TestUnicodeGrammar.tssoon │ ├── TestVocabulary.ts │ ├── TestXPath.g4 │ └── TestXPath.ts ├── tool ├── LICENSE ├── README.md ├── antlr4ts ├── index.js ├── package-lock.json ├── package.json ├── pom.xml ├── resources │ └── org │ │ └── antlr │ │ └── v4 │ │ └── tool │ │ └── templates │ │ └── codegen │ │ └── TypeScript │ │ └── TypeScript.stg ├── src │ └── org │ │ └── antlr │ │ └── v4 │ │ ├── TypeScriptTool.java │ │ └── codegen │ │ └── target │ │ └── TypeScriptTarget.java ├── test │ └── org │ │ └── antlr │ │ └── v4 │ │ └── test │ │ └── runtime │ │ └── typescript │ │ ├── BaseTest.java │ │ ├── ErrorQueue.java │ │ ├── TypeScript.test.stg │ │ ├── package.json │ │ └── tsconfig.json └── tsconfig.json ├── tsconfig.json └── tslint.json /.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: Visual Studio 2015 3 | init: 4 | - git config --global core.autocrlf true 5 | install: 6 | - ps: Install-Product node 10 7 | - npm install -g npm@6 8 | branches: 9 | only: 10 | - master 11 | environment: 12 | JAVA6_HOME: C:/Program Files/Java/jdk1.6.0/jre 13 | build_script: 14 | - npm install 15 | - npm run tslint 16 | - npm run pack-tool 17 | - npm run pack-runtime 18 | test_script: 19 | - npm test 20 | artifacts: 21 | - path: 'antlr4ts-*.tgz' 22 | cache: 23 | - node_modules -> **\package.json 24 | - C:\Users\appveyor\.m2 -> **\pom.xml 25 | -------------------------------------------------------------------------------- /.codecov.yml: -------------------------------------------------------------------------------- 1 | # https://docs.codecov.io/docs/codecov-yaml 2 | # https://github.com/codecov/support/wiki/Codecov-Yaml 3 | 4 | coverage: 5 | status: 6 | project: 7 | default: false 8 | patch: 9 | default: false 10 | 11 | comment: 12 | layout: "diff" 13 | 14 | flags: 15 | production: 16 | paths: 17 | - src/ 18 | test: 19 | paths: 20 | - benchmark/ 21 | - test/ 22 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.] 4 | indent_style = tab 5 | tab_width = 4 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | 9 | [*.{ts,js,g4}] 10 | indent_style = tab 11 | tab_width = 4 12 | insert_final_newline = true 13 | trim_trailing_whitespace = true 14 | 15 | [*.json] 16 | indent_style = space 17 | indent_size = 2 18 | insert_final_newline = true 19 | trim_trailing_whitespace = true 20 | 21 | [.{gitignore,gitattributes,editorconfig}] 22 | insert_final_newline = true 23 | trim_trailing_whitespace = true 24 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto-detect text files for everything not explicitly listed below 2 | * text=auto 3 | 4 | /tool/antlr4ts eol=lf 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs/ 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids/ 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov/ 13 | 14 | # istanbul code coverage data & report 15 | coverage/ 16 | 17 | # nyc test coverage 18 | .nyc_output/ 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt/ 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release/ 28 | 29 | # Dependency directories 30 | node_modules/ 31 | jspm_packages/ 32 | 33 | # Optional npm cache directory 34 | .npm/ 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # Build products 40 | /src/tree/xpath/XPathLexer.interp 41 | /src/tree/xpath/XPathLexer.tokens 42 | /src/tree/xpath/XPathLexer.ts 43 | gen/ 44 | /target/ 45 | /tool/target/ 46 | doc/ 47 | 48 | # Visual Studio build output and per-user files 49 | obj/ 50 | bin/ 51 | .vs/ 52 | *.user 53 | 54 | # Java IDEs 55 | .idea/ 56 | *.iml 57 | 58 | # ALM IDE 59 | .alm/ 60 | 61 | # NPM pack output 62 | *.tgz 63 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "reference/antlr4"] 2 | path = reference/antlr4 3 | url = https://github.com/tunnelvisionlabs/antlr4.git 4 | branch = master 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - "10" 5 | jdk: openjdk6 6 | before_install: 7 | - npm install -g npm@6 8 | - npm install -g codecov 9 | before_script: 10 | - export NODE_OPTIONS=--max_old_space_size=4096 11 | script: 12 | # npm install is run automatically by Travis before 'script' 13 | - nyc --reporter=none mocha --timeout=10000 --require 'source-map-support/register' './target/test/**/*.js' 14 | - nyc report --reporter=text-lcov > coverage.lcov 15 | - codecov 16 | - npm run tslint 17 | - npm run pack-tool 18 | - npm run pack-runtime 19 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug Tests", 6 | "type": "node", 7 | "request": "launch", 8 | "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", 9 | "stopOnEntry": false, 10 | "args": [ 11 | "--debug", "-R", "dot" 12 | ], 13 | "cwd": "${workspaceRoot}", 14 | "preLaunchTask": "tsc", 15 | "runtimeExecutable": null, 16 | "runtimeArgs": [ 17 | "--nolazy" 18 | ], 19 | "env": { 20 | "NODE_ENV": "development" 21 | }, 22 | "console": "integratedTerminal", 23 | "sourceMaps": true, 24 | "outDir": "${workspaceRoot}/target" 25 | }, 26 | { 27 | "name": "Attach", 28 | "type": "node", 29 | "request": "attach", 30 | "port": 5858, 31 | "address": "localhost", 32 | "restart": false, 33 | "sourceMaps": true, 34 | "outDir": null, 35 | "localRoot": "${workspaceRoot}", 36 | "remoteRoot": null 37 | }, 38 | { 39 | "name": "Attach to Process", 40 | "type": "node", 41 | "request": "attach", 42 | "processId": "${command.PickProcess}", 43 | "port": 5858, 44 | "sourceMaps": true, 45 | "outDir": "${workspaceRoot}/target" 46 | } 47 | ] 48 | } 49 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "typescript.tsdk": "./node_modules/typescript/lib", 4 | "editor.rulers": [ 5 | 120 6 | ] 7 | } -------------------------------------------------------------------------------- /.vscode/spell.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "en", 3 | "ignoreWordsList": [ 4 | "npm", 5 | "ANTLR", 6 | "antlr4ts", 7 | "runtime-testsuite", 8 | "NPM" 9 | ], 10 | "mistakeTypeToStatus": { 11 | "Passive voice": "Hint", 12 | "Spelling": "Error", 13 | "Complex Expression": "Disable", 14 | "Hidden Verbs": "Information", 15 | "Hyphen Required": "Disable", 16 | "Redundant Expression": "Disable", 17 | "Did you mean...": "Disable", 18 | "Repeated Word": "Warning", 19 | "Missing apostrophe": "Warning", 20 | "Cliches": "Disable", 21 | "Missing Word": "Disable", 22 | "Make I uppercase": "Warning" 23 | }, 24 | "languageIDs": [ 25 | "markdown", 26 | "plaintext" 27 | ], 28 | "ignoreRegExp": [ 29 | "/\\(.*\\.(jpg|jpeg|png|md|gif|JPG|JPEG|PNG|MD|GIF)\\)/g", 30 | "/((http|https|ftp|git)\\S*)/g" 31 | ] 32 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "command": "npm", 6 | "type": "shell", 7 | "args": ["run", "tsc-watch"], 8 | "presentation": { 9 | "echo": true, 10 | "reveal": "silent", 11 | "focus": false, 12 | "panel": "shared", 13 | "showReuseMessage": true, 14 | "clear": false 15 | }, 16 | "isBackground": true, 17 | "problemMatcher": "$tsc" 18 | } 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | [The "BSD license"] 2 | Copyright (c) 2016 The ANTLR Project 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions 7 | are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 2. Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in the 13 | documentation and/or other materials provided with the distribution. 14 | 3. Neither the name of the copyright holder nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 19 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 20 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 22 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 23 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 27 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /antlr4ts.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "antlr4ts", "antlr4ts.njsproj", "{D6642AE4-3C11-4A8F-B700-F844AFCBDD94}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {D6642AE4-3C11-4A8F-B700-F844AFCBDD94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {D6642AE4-3C11-4A8F-B700-F844AFCBDD94}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {D6642AE4-3C11-4A8F-B700-F844AFCBDD94}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {D6642AE4-3C11-4A8F-B700-F844AFCBDD94}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /benchmark/Graphemes.g4: -------------------------------------------------------------------------------- 1 | grammar Graphemes; 2 | 3 | Extend: [\p{Grapheme_Cluster_Break=Extend}]; 4 | ZWJ: '\u200D'; 5 | SpacingMark: [\p{Grapheme_Cluster_Break=SpacingMark}]; 6 | fragment VS15: '\uFE0E'; 7 | fragment VS16: '\uFE0F'; 8 | fragment NonspacingMark: [\p{Nonspacing_Mark}]; 9 | fragment TextPresentationCharacter: [\p{EmojiPresentation=TextDefault}]; 10 | fragment EmojiPresentationCharacter: [\p{EmojiPresentation=EmojiDefault}]; 11 | fragment TextPresentationSequence: EmojiPresentationCharacter VS15; 12 | fragment EmojiPresentationSequence: TextPresentationCharacter VS16; 13 | fragment EmojiModifierSequence: 14 | [\p{Grapheme_Cluster_Break=E_Base}\p{Grapheme_Cluster_Break=E_Base_GAZ}] [\p{Grapheme_Cluster_Break=E_Modifier}]; 15 | fragment EmojiFlagSequence: 16 | [\p{Grapheme_Cluster_Break=Regional_Indicator}] [\p{Grapheme_Cluster_Break=Regional_Indicator}]; 17 | fragment ExtendedPictographic: [\p{Extended_Pictographic}]; 18 | fragment EmojiNRK: [\p{EmojiNRK}]; 19 | fragment EmojiCombiningSequence: 20 | ( EmojiPresentationSequence 21 | | TextPresentationSequence 22 | | EmojiPresentationCharacter ) 23 | NonspacingMark*; 24 | EmojiCoreSequence: 25 | EmojiModifierSequence 26 | | EmojiCombiningSequence 27 | | EmojiFlagSequence; 28 | fragment EmojiZWJElement: 29 | EmojiModifierSequence 30 | | EmojiPresentationSequence 31 | | EmojiPresentationCharacter 32 | | ExtendedPictographic 33 | | EmojiNRK; 34 | EmojiZWJSequence: 35 | EmojiZWJElement (ZWJ EmojiZWJElement)+; 36 | emojiSequence: 37 | ( EmojiZWJSequence 38 | | EmojiCoreSequence ) 39 | ( Extend | ZWJ | SpacingMark )*; 40 | 41 | Prepend: [\p{Grapheme_Cluster_Break=Prepend}]; 42 | NonControl: [\P{Grapheme_Cluster_Break=Control}]; 43 | CRLF: [\p{Grapheme_Cluster_Break=CR}][\p{Grapheme_Cluster_Break=LF}]; 44 | HangulSyllable: 45 | [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=V}]+ [\p{Grapheme_Cluster_Break=T}]* 46 | | [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LV}] [\p{Grapheme_Cluster_Break=V}]* [\p{Grapheme_Cluster_Break=T}]* 47 | | [\p{Grapheme_Cluster_Break=L}]* [\p{Grapheme_Cluster_Break=LVT}] [\p{Grapheme_Cluster_Break=T}]* 48 | | [\p{Grapheme_Cluster_Break=L}]+ 49 | | [\p{Grapheme_Cluster_Break=T}]+; 50 | 51 | graphemeCluster: 52 | CRLF 53 | | Prepend* ( emojiSequence | HangulSyllable | NonControl ) ( Extend | ZWJ | SpacingMark )*; 54 | 55 | graphemes: graphemeCluster* EOF; 56 | -------------------------------------------------------------------------------- /benchmark/Stopwatch.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { TimeSpan } from "./TimeSpan"; 7 | 8 | export class Stopwatch { 9 | private _elapsed: number[] = [0, 0]; 10 | private _start?: number[]; 11 | 12 | public static startNew(): Stopwatch { 13 | let result = new Stopwatch(); 14 | result.start(); 15 | return result; 16 | } 17 | 18 | public start(): void { 19 | if (this._start !== undefined) { 20 | throw new Error("The stopwatch is already started."); 21 | } 22 | 23 | this._start = process.hrtime(); 24 | } 25 | 26 | public elapsed(): TimeSpan { 27 | let result = { seconds: this._elapsed[0], nanos: this._elapsed[1] }; 28 | if (this._start !== undefined) { 29 | let stop = process.hrtime(); 30 | result.seconds += stop[0] - this._start[0]; 31 | if (stop[0] === this._start[0]) { 32 | result.nanos += stop[1] - this._start[1]; 33 | } else { 34 | result.nanos += TimeSpan.NANOS_PER_SECOND - this._start[1] + stop[1]; 35 | } 36 | } 37 | 38 | while (result.nanos > TimeSpan.NANOS_PER_SECOND) { 39 | result.seconds++; 40 | result.nanos -= TimeSpan.NANOS_PER_SECOND; 41 | } 42 | 43 | return new TimeSpan(result.seconds, result.nanos); 44 | } 45 | 46 | public elapsedMillis(): number { 47 | return this.elapsed().totalMilliseconds; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /benchmark/TimeSpan.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export class TimeSpan { 7 | public readonly seconds: number; 8 | public readonly nanos: number; 9 | 10 | constructor(seconds: number, nanos: number) { 11 | this.seconds = seconds; 12 | this.nanos = nanos; 13 | } 14 | 15 | public static fromMilliseconds(millis: number): TimeSpan { 16 | let seconds = Math.trunc(millis / TimeSpan.MILLIS_PER_SECOND); 17 | let nanos = (millis - (seconds * TimeSpan.MILLIS_PER_SECOND)) * TimeSpan.NANOS_PER_MILLISECOND; 18 | return new TimeSpan(seconds, nanos); 19 | } 20 | 21 | public get totalMilliseconds(): number { 22 | return (this.seconds * TimeSpan.MILLIS_PER_SECOND) + (this.nanos / TimeSpan.NANOS_PER_MILLISECOND); 23 | } 24 | 25 | public get totalMicroseconds(): number { 26 | return (this.seconds * TimeSpan.MICROS_PER_SECOND) + (this.nanos / TimeSpan.NANOS_PER_MICROSECOND); 27 | } 28 | } 29 | 30 | export namespace TimeSpan { 31 | export const MILLIS_PER_SECOND: number = 1000; 32 | export const MICROS_PER_SECOND: number = 1000000; 33 | export const NANOS_PER_SECOND: number = 1000000000; 34 | export const NANOS_PER_MICROSECOND: number = 1000; 35 | export const NANOS_PER_MILLISECOND: number = 1000000; 36 | } 37 | -------------------------------------------------------------------------------- /benchmark/emoji.txt: -------------------------------------------------------------------------------- 1 | 😀🖖💩 2 | 👴🏽🖖🏿👦🏼 3 | 👮‍♀️👷‍♀️👯‍♂️ 4 | 🙇🏻‍♀️👼🏽🎅🏿 5 | 01234 6 | 0️⃣1️⃣2️⃣3️⃣4️⃣ 7 | ™©® 8 | ™️©️®️ 9 | 🇨🇨🇧🇬🇯🇲 10 | 🏳️‍🌈 11 | 🏴‍☠️ 12 | 13 | -------------------------------------------------------------------------------- /reference/.editorconfig: -------------------------------------------------------------------------------- 1 | # Ensure the .editorconfig for our project does not propagate to files brought in from other repositories 2 | root = true 3 | -------------------------------------------------------------------------------- /src/ANTLRErrorListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:48.7499997-07:00 7 | 8 | /** How to emit recognition errors. */ 9 | import { Recognizer } from "./Recognizer"; 10 | import { RecognitionException } from "./RecognitionException"; 11 | 12 | export interface ANTLRErrorListener { 13 | /** 14 | * Upon syntax error, notify any interested parties. This is not how to 15 | * recover from errors or compute error messages. {@link ANTLRErrorStrategy} 16 | * specifies how to recover from syntax errors and how to compute error 17 | * messages. This listener's job is simply to emit a computed message, 18 | * though it has enough information to create its own message in many cases. 19 | * 20 | * The {@link RecognitionException} is non-`undefined` for all syntax errors except 21 | * when we discover mismatched token errors that we can recover from 22 | * in-line, without returning from the surrounding rule (via the single 23 | * token insertion and deletion mechanism). 24 | * 25 | * @param recognizer 26 | * What parser got the error. From this 27 | * object, you can access the context as well 28 | * as the input stream. 29 | * @param offendingSymbol 30 | * The offending token in the input token 31 | * stream, unless recognizer is a lexer (then it's `undefined`). If 32 | * no viable alternative error, `e` has token at which we 33 | * started production for the decision. 34 | * @param line 35 | * The line number in the input where the error occurred. 36 | * @param charPositionInLine 37 | * The character position within that line where the error occurred. 38 | * @param msg 39 | * The message to emit. 40 | * @param e 41 | * The exception generated by the parser that led to 42 | * the reporting of an error. It is `undefined` in the case where 43 | * the parser was able to recover in line without exiting the 44 | * surrounding rule. 45 | */ 46 | syntaxError?: ( 47 | /*@NotNull*/ 48 | recognizer: Recognizer, 49 | offendingSymbol: T | undefined, 50 | line: number, 51 | charPositionInLine: number, 52 | /*@NotNull*/ 53 | msg: string, 54 | e: RecognitionException | undefined) => void; 55 | } 56 | -------------------------------------------------------------------------------- /src/ANTLRFileStream.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | // ConvertTo-TS run at 2016-10-04T11:26:49.0009449-07:00 6 | 7 | /** 8 | * This is an {@link ANTLRInputStream} that is loaded from a file all at once 9 | * when you construct the object. 10 | * 11 | * @deprecated as of 4.7 Please use {@link CharStreams} interface. 12 | */ 13 | export class ANTLRFileStream extends ANTLRInputStream { 14 | protected fileName: string; 15 | 16 | constructor(@NotNull fileName: string) { 17 | this(fileName, null); 18 | } 19 | 20 | constructor1(@NotNull fileName: string, encoding: string) { 21 | this.fileName = fileName; 22 | load(fileName, encoding); 23 | } 24 | 25 | load(@NotNull fileName: string, @Nullable encoding: string): void 26 | 27 | { 28 | data = Utils.readFile(fileName, encoding); 29 | this.n = data.length; 30 | } 31 | 32 | @Override 33 | get sourceName(): string { 34 | return fileName; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CharStream.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:50.0659297-07:00 7 | 8 | import { Interval } from "./misc/Interval"; 9 | import { IntStream } from "./IntStream"; 10 | 11 | /** A source of characters for an ANTLR lexer. */ 12 | export interface CharStream extends IntStream { 13 | /** 14 | * This method returns the text for a range of characters within this input 15 | * stream. This method is guaranteed to not throw an exception if the 16 | * specified `interval` lies entirely within a marked range. For more 17 | * information about marked ranges, see {@link IntStream#mark}. 18 | * 19 | * @param interval an interval within the stream 20 | * @returns the text of the specified interval 21 | * 22 | * @throws NullPointerException if `interval` is `undefined` 23 | * @throws IllegalArgumentException if `interval.a < 0`, or if 24 | * `interval.b < interval.a - 1`, or if `interval.b` lies at or 25 | * past the end of the stream 26 | * @throws UnsupportedOperationException if the stream does not support 27 | * getting the text of the specified interval 28 | */ 29 | //@NotNull 30 | getText(/*@NotNull*/ interval: Interval): string; 31 | } 32 | -------------------------------------------------------------------------------- /src/ConsoleErrorListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:50.5479602-07:00 7 | 8 | import { ANTLRErrorListener } from "./ANTLRErrorListener"; 9 | import { RecognitionException } from "./RecognitionException"; 10 | import { Recognizer } from "./Recognizer"; 11 | 12 | /** 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class ConsoleErrorListener implements ANTLRErrorListener { 17 | /** 18 | * Provides a default instance of {@link ConsoleErrorListener}. 19 | */ 20 | public static readonly INSTANCE: ConsoleErrorListener = new ConsoleErrorListener(); 21 | 22 | /** 23 | * {@inheritDoc} 24 | * 25 | * This implementation prints messages to {@link System#err} containing the 26 | * values of `line`, `charPositionInLine`, and `msg` using 27 | * the following format. 28 | * 29 | *
30 | 	 * line *line*:*charPositionInLine* *msg*
31 | 	 * 
32 | */ 33 | public syntaxError( 34 | recognizer: Recognizer, 35 | offendingSymbol: T, 36 | line: number, 37 | charPositionInLine: number, 38 | msg: string, 39 | e: RecognitionException | undefined): void { 40 | console.error(`line ${line}:${charPositionInLine} ${msg}`); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Decorators.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export function NotNull( 7 | target: any, 8 | propertyKey: PropertyKey, 9 | propertyDescriptor?: PropertyDescriptor | number) { 10 | // intentionally empty 11 | } 12 | 13 | export function Nullable( 14 | target: any, 15 | propertyKey: PropertyKey, 16 | propertyDescriptor?: PropertyDescriptor | number) { 17 | // intentionally empty 18 | } 19 | 20 | export function Override( 21 | target: any, 22 | propertyKey: PropertyKey, 23 | propertyDescriptor?: PropertyDescriptor) { 24 | // do something with 'target' ... 25 | } 26 | 27 | export function SuppressWarnings(options: string) { 28 | return (target: any, propertyKey: PropertyKey, descriptor?: PropertyDescriptor) => { 29 | // intentionally empty 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/Dependents.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:51.1349829-07:00 7 | 8 | /** 9 | * 10 | * @author Sam Harwell 11 | */ 12 | export enum Dependents { 13 | 14 | /** 15 | * The element is dependent upon the specified rule. 16 | */ 17 | SELF, 18 | /** 19 | * The element is dependent upon the set of the specified rule's parents 20 | * (rules which directly reference it). 21 | */ 22 | PARENTS, 23 | /** 24 | * The element is dependent upon the set of the specified rule's children 25 | * (rules which it directly references). 26 | */ 27 | CHILDREN, 28 | /** 29 | * The element is dependent upon the set of the specified rule's ancestors 30 | * (the transitive closure of `PARENTS` rules). 31 | */ 32 | ANCESTORS, 33 | /** 34 | * The element is dependent upon the set of the specified rule's descendants 35 | * (the transitive closure of `CHILDREN` rules). 36 | */ 37 | DESCENDANTS, 38 | /** 39 | * The element is dependent upon the set of the specified rule's siblings 40 | * (the union of `CHILDREN` of its `PARENTS`). 41 | */ 42 | SIBLINGS, 43 | /** 44 | * The element is dependent upon the set of the specified rule's preceeding 45 | * siblings (the union of `CHILDREN` of its `PARENTS` which 46 | * appear before a reference to the rule). 47 | */ 48 | PRECEEDING_SIBLINGS, 49 | /** 50 | * The element is dependent upon the set of the specified rule's following 51 | * siblings (the union of `CHILDREN` of its `PARENTS` which 52 | * appear after a reference to the rule). 53 | */ 54 | FOLLOWING_SIBLINGS, 55 | /** 56 | * The element is dependent upon the set of the specified rule's preceeding 57 | * elements (rules which might end before the start of the specified rule 58 | * while parsing). This is calculated by taking the 59 | * `PRECEEDING_SIBLINGS` of the rule and each of its 60 | * `ANCESTORS`, along with the `DESCENDANTS` of those 61 | * elements. 62 | */ 63 | PRECEEDING, 64 | /** 65 | * The element is dependent upon the set of the specified rule's following 66 | * elements (rules which might start after the end of the specified rule 67 | * while parsing). This is calculated by taking the 68 | * `FOLLOWING_SIBLINGS` of the rule and each of its 69 | * `ANCESTORS`, along with the `DESCENDANTS` of those 70 | * elements. 71 | */ 72 | FOLLOWING, 73 | } 74 | -------------------------------------------------------------------------------- /src/FailedPredicateException.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:51.4099946-07:00 7 | 8 | import { AbstractPredicateTransition } from "./atn/AbstractPredicateTransition"; 9 | import { ATN } from "./atn/ATN"; 10 | import { ATNState } from "./atn/ATNState"; 11 | import { Parser } from "./Parser"; 12 | import { RecognitionException } from "./RecognitionException"; 13 | import { Recognizer } from "./Recognizer"; 14 | import { NotNull } from "./Decorators"; 15 | import { PredicateTransition } from "./atn/PredicateTransition"; 16 | 17 | /** A semantic predicate failed during validation. Validation of predicates 18 | * occurs when normally parsing the alternative just like matching a token. 19 | * Disambiguating predicate evaluation occurs when we test a predicate during 20 | * prediction. 21 | */ 22 | export class FailedPredicateException extends RecognitionException { 23 | //private static serialVersionUID: number = 5379330841495778709L; 24 | 25 | private _ruleIndex: number; 26 | private _predicateIndex: number; 27 | private _predicate?: string; 28 | 29 | constructor(@NotNull recognizer: Parser, predicate?: string, message?: string) { 30 | super( 31 | recognizer, 32 | recognizer.inputStream, 33 | recognizer.context, 34 | FailedPredicateException.formatMessage(predicate, message)); 35 | let s: ATNState = recognizer.interpreter.atn.states[recognizer.state]; 36 | 37 | let trans = s.transition(0) as AbstractPredicateTransition; 38 | if (trans instanceof PredicateTransition) { 39 | this._ruleIndex = trans.ruleIndex; 40 | this._predicateIndex = trans.predIndex; 41 | } 42 | else { 43 | this._ruleIndex = 0; 44 | this._predicateIndex = 0; 45 | } 46 | 47 | this._predicate = predicate; 48 | super.setOffendingToken(recognizer, recognizer.currentToken); 49 | } 50 | 51 | get ruleIndex(): number { 52 | return this._ruleIndex; 53 | } 54 | 55 | get predicateIndex(): number { 56 | return this._predicateIndex; 57 | } 58 | 59 | get predicate(): string | undefined { 60 | return this._predicate; 61 | } 62 | 63 | @NotNull 64 | private static formatMessage(predicate: string | undefined, message: string | undefined): string { 65 | if (message) { 66 | return message; 67 | } 68 | 69 | return `failed predicate: {${predicate}}?`; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/InputMismatchException.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:51.5187682-07:00 7 | 8 | import { RecognitionException } from "./RecognitionException"; 9 | import { NotNull } from "./Decorators"; 10 | import { Parser } from "./Parser"; 11 | import { ParserRuleContext } from "./ParserRuleContext"; 12 | 13 | /** This signifies any kind of mismatched input exceptions such as 14 | * when the current input does not match the expected token. 15 | */ 16 | export class InputMismatchException extends RecognitionException { 17 | //private static serialVersionUID: number = 1532568338707443067L; 18 | 19 | constructor(/*@NotNull*/ recognizer: Parser); 20 | constructor(/*@NotNull*/ recognizer: Parser, state: number, context: ParserRuleContext); 21 | constructor(@NotNull recognizer: Parser, state?: number, context?: ParserRuleContext) { 22 | if (context === undefined) { 23 | context = recognizer.context; 24 | } 25 | 26 | super(recognizer, recognizer.inputStream, context); 27 | 28 | if (state !== undefined) { 29 | this.setOffendingState(state); 30 | } 31 | 32 | this.setOffendingToken(recognizer, recognizer.currentToken); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/InterpreterRuleContext.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:51.5898546-07:00 7 | 8 | import { Override } from "./Decorators"; 9 | import { ParserRuleContext } from "./ParserRuleContext"; 10 | 11 | /** 12 | * This class extends {@link ParserRuleContext} by allowing the value of 13 | * {@link #getRuleIndex} to be explicitly set for the context. 14 | * 15 | * {@link ParserRuleContext} does not include field storage for the rule index 16 | * since the context classes created by the code generator override the 17 | * {@link #getRuleIndex} method to return the correct value for that context. 18 | * Since the parser interpreter does not use the context classes generated for a 19 | * parser, this class (with slightly more memory overhead per node) is used to 20 | * provide equivalent functionality. 21 | */ 22 | export class InterpreterRuleContext extends ParserRuleContext { 23 | /** 24 | * This is the backing field for {@link #getRuleIndex}. 25 | */ 26 | private _ruleIndex: number; 27 | 28 | constructor(ruleIndex: number); 29 | 30 | /** 31 | * Constructs a new {@link InterpreterRuleContext} with the specified 32 | * parent, invoking state, and rule index. 33 | * 34 | * @param ruleIndex The rule index for the current context. 35 | * @param parent The parent context. 36 | * @param invokingStateNumber The invoking state number. 37 | */ 38 | constructor(ruleIndex: number, parent: ParserRuleContext | undefined, invokingStateNumber: number); 39 | 40 | constructor(ruleIndex: number, parent?: ParserRuleContext, invokingStateNumber?: number) { 41 | if (invokingStateNumber !== undefined) { 42 | super(parent, invokingStateNumber); 43 | } else { 44 | super(); 45 | } 46 | 47 | this._ruleIndex = ruleIndex; 48 | } 49 | 50 | @Override 51 | get ruleIndex(): number { 52 | return this._ruleIndex; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/LexerInterpreter.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:51.9954566-07:00 7 | 8 | import { ATN } from "./atn/ATN"; 9 | import { ATNType } from "./atn/ATNType"; 10 | import { CharStream } from "./CharStream"; 11 | import { Lexer } from "./Lexer"; 12 | import { LexerATNSimulator } from "./atn/LexerATNSimulator"; 13 | import { NotNull } from "./Decorators"; 14 | import { Override } from "./Decorators"; 15 | import { Vocabulary } from "./Vocabulary"; 16 | 17 | export class LexerInterpreter extends Lexer { 18 | protected _grammarFileName: string; 19 | protected _atn: ATN; 20 | 21 | protected _ruleNames: string[]; 22 | protected _channelNames: string[]; 23 | protected _modeNames: string[]; 24 | @NotNull 25 | private _vocabulary: Vocabulary; 26 | 27 | constructor(grammarFileName: string, @NotNull vocabulary: Vocabulary, ruleNames: string[], channelNames: string[], modeNames: string[], atn: ATN, input: CharStream) { 28 | super(input); 29 | 30 | if (atn.grammarType !== ATNType.LEXER) { 31 | throw new Error("IllegalArgumentException: The ATN must be a lexer ATN."); 32 | } 33 | 34 | this._grammarFileName = grammarFileName; 35 | this._atn = atn; 36 | 37 | this._ruleNames = ruleNames.slice(0); 38 | this._channelNames = channelNames.slice(0); 39 | this._modeNames = modeNames.slice(0); 40 | this._vocabulary = vocabulary; 41 | this._interp = new LexerATNSimulator(atn, this); 42 | } 43 | 44 | @Override 45 | get atn(): ATN { 46 | return this._atn; 47 | } 48 | 49 | @Override 50 | get grammarFileName(): string { 51 | return this._grammarFileName; 52 | } 53 | 54 | @Override 55 | get ruleNames(): string[] { 56 | return this._ruleNames; 57 | } 58 | 59 | @Override 60 | get channelNames(): string[] { 61 | return this._channelNames; 62 | } 63 | 64 | @Override 65 | get modeNames(): string[] { 66 | return this._modeNames; 67 | } 68 | 69 | @Override 70 | get vocabulary(): Vocabulary { 71 | return this._vocabulary; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/LexerNoViableAltException.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:52.0961136-07:00 7 | 8 | import { ATNConfigSet } from "./atn/ATNConfigSet"; 9 | import { RecognitionException } from "./RecognitionException"; 10 | import { NotNull, Override } from "./Decorators"; 11 | import { Lexer } from "./Lexer"; 12 | import { CharStream } from "./CharStream"; 13 | import { Interval } from "./misc/Interval"; 14 | import * as Utils from "./misc/Utils"; 15 | 16 | export class LexerNoViableAltException extends RecognitionException { 17 | //private static serialVersionUID: number = -730999203913001726L; 18 | 19 | /** Matching attempted at what input index? */ 20 | private _startIndex: number; 21 | 22 | /** Which configurations did we try at input.index that couldn't match input.LA(1)? */ 23 | private _deadEndConfigs?: ATNConfigSet; 24 | 25 | constructor( 26 | lexer: Lexer | undefined, 27 | @NotNull input: CharStream, 28 | startIndex: number, 29 | deadEndConfigs: ATNConfigSet | undefined) { 30 | super(lexer, input); 31 | this._startIndex = startIndex; 32 | this._deadEndConfigs = deadEndConfigs; 33 | } 34 | 35 | get startIndex(): number { 36 | return this._startIndex; 37 | } 38 | 39 | get deadEndConfigs(): ATNConfigSet | undefined { 40 | return this._deadEndConfigs; 41 | } 42 | 43 | @Override 44 | get inputStream(): CharStream { 45 | return super.inputStream as CharStream; 46 | } 47 | 48 | @Override 49 | public toString(): string { 50 | let symbol = ""; 51 | if (this._startIndex >= 0 && this._startIndex < this.inputStream.size) { 52 | symbol = this.inputStream.getText(Interval.of(this._startIndex, this._startIndex)); 53 | symbol = Utils.escapeWhitespace(symbol, false); 54 | } 55 | 56 | // return String.format(Locale.getDefault(), "%s('%s')", LexerNoViableAltException.class.getSimpleName(), symbol); 57 | return `LexerNoViableAltException('${symbol}')`; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/ProxyErrorListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:56.8126690-07:00 7 | import { ANTLRErrorListener } from "./ANTLRErrorListener"; 8 | import { RecognitionException } from "./RecognitionException"; 9 | import { Recognizer } from "./Recognizer"; 10 | import { Override, NotNull } from "./Decorators"; 11 | 12 | /** 13 | * This implementation of {@link ANTLRErrorListener} dispatches all calls to a 14 | * collection of delegate listeners. This reduces the effort required to support multiple 15 | * listeners. 16 | * 17 | * @author Sam Harwell 18 | */ 19 | export class ProxyErrorListener> implements ANTLRErrorListener { 20 | 21 | constructor(private delegates: TListener[]) { 22 | if (!delegates) { 23 | throw new Error("Invalid delegates"); 24 | } 25 | } 26 | 27 | protected getDelegates(): ReadonlyArray { 28 | return this.delegates; 29 | } 30 | 31 | @Override 32 | public syntaxError( 33 | @NotNull recognizer: Recognizer, 34 | offendingSymbol: T | undefined, 35 | line: number, 36 | charPositionInLine: number, 37 | @NotNull msg: string, 38 | e: RecognitionException | undefined): void { 39 | this.delegates.forEach((listener) => { 40 | if (listener.syntaxError) { 41 | listener.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e); 42 | } 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/ProxyParserErrorListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:56.9812284-07:00 7 | import { ANTLRErrorListener } from "./ANTLRErrorListener"; 8 | import { ATNConfigSet } from "./atn/ATNConfigSet"; 9 | import { BitSet } from "./misc/BitSet"; 10 | import { DFA } from "./dfa/DFA"; 11 | import { Parser } from "./Parser"; 12 | import { RecognitionException } from "./RecognitionException"; 13 | import { Recognizer } from "./Recognizer"; 14 | import { ProxyErrorListener } from "./ProxyErrorListener"; 15 | import { ParserErrorListener } from "./ParserErrorListener"; 16 | import { SimulatorState } from "./atn/SimulatorState"; 17 | import { Token } from "./Token"; 18 | import { Override } from "./Decorators"; 19 | 20 | /** 21 | * @author Sam Harwell 22 | */ 23 | export class ProxyParserErrorListener extends ProxyErrorListener 24 | implements ParserErrorListener { 25 | 26 | constructor(delegates: ParserErrorListener[]) { 27 | super(delegates); 28 | } 29 | 30 | @Override 31 | public reportAmbiguity( 32 | recognizer: Parser, 33 | dfa: DFA, 34 | startIndex: number, 35 | stopIndex: number, 36 | exact: boolean, 37 | ambigAlts: BitSet | undefined, 38 | configs: ATNConfigSet): void { 39 | this.getDelegates() 40 | .forEach((listener) => { 41 | if (listener.reportAmbiguity) { 42 | listener.reportAmbiguity( 43 | recognizer, 44 | dfa, 45 | startIndex, 46 | stopIndex, 47 | exact, 48 | ambigAlts, 49 | configs); 50 | } 51 | 52 | }); 53 | } 54 | 55 | @Override 56 | public reportAttemptingFullContext( 57 | recognizer: Parser, 58 | dfa: DFA, 59 | startIndex: number, 60 | stopIndex: number, 61 | conflictingAlts: BitSet | undefined, 62 | conflictState: SimulatorState): void { 63 | this.getDelegates() 64 | .forEach((listener) => { 65 | if (listener.reportAttemptingFullContext) { 66 | listener.reportAttemptingFullContext( 67 | recognizer, 68 | dfa, 69 | startIndex, 70 | stopIndex, 71 | conflictingAlts, 72 | conflictState); 73 | } 74 | }); 75 | } 76 | 77 | @Override 78 | public reportContextSensitivity( 79 | recognizer: Parser, 80 | dfa: DFA, 81 | startIndex: number, 82 | stopIndex: number, 83 | prediction: number, 84 | acceptState: SimulatorState): void { 85 | this.getDelegates() 86 | .forEach((listener) => { 87 | if (listener.reportContextSensitivity) { 88 | listener.reportContextSensitivity( 89 | recognizer, 90 | dfa, 91 | startIndex, 92 | stopIndex, 93 | prediction, 94 | acceptState); 95 | } 96 | }); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/RuleContextWithAltNum.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:57.4741196-07:00 7 | 8 | import { ATN } from "./atn/ATN"; 9 | import { Override } from "./Decorators"; 10 | import { ParserRuleContext } from "./ParserRuleContext"; 11 | 12 | /** A handy class for use with 13 | * 14 | * options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;} 15 | * 16 | * that provides a backing field / impl for the outer alternative number 17 | * matched for an internal parse tree node. 18 | * 19 | * I'm only putting into Java runtime as I'm certain I'm the only one that 20 | * will really every use this. 21 | */ 22 | export class RuleContextWithAltNum extends ParserRuleContext { 23 | private _altNumber: number; 24 | 25 | constructor(); 26 | constructor(parent: ParserRuleContext | undefined, invokingStateNumber: number); 27 | constructor(parent?: ParserRuleContext, invokingStateNumber?: number) { 28 | if (invokingStateNumber !== undefined) { 29 | super(parent, invokingStateNumber); 30 | } else { 31 | super(); 32 | } 33 | 34 | this._altNumber = ATN.INVALID_ALT_NUMBER; 35 | } 36 | 37 | @Override 38 | get altNumber(): number { 39 | return this._altNumber; 40 | } 41 | 42 | // @Override 43 | set altNumber(altNum: number) { 44 | this._altNumber = altNum; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/RuleDependency.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:57.6271221-07:00 7 | 8 | import { Dependents } from "./Dependents"; 9 | import { Parser } from "./Parser"; 10 | 11 | /** 12 | * Declares a dependency upon a grammar rule, along with a set of zero or more dependent rules. 13 | * 14 | * Version numbers within a grammar should be assigned on a monotonically increasing basis to allow for accurate 15 | * tracking of dependent rules. 16 | * 17 | * @author Sam Harwell 18 | */ 19 | export function RuleDependency(dependency: DependencySpecification) { 20 | return (target: object, propertyKey: PropertyKey, propertyDescriptor: PropertyDescriptor) => { 21 | // intentionally empty 22 | }; 23 | } 24 | 25 | export interface DependencySpecification { 26 | readonly recognizer: { new (...args: any[]): Parser; }; 27 | 28 | readonly rule: number; 29 | 30 | readonly version: number; 31 | 32 | /** 33 | * Specifies the set of grammar rules related to `rule` which the annotated element depends on. Even when absent 34 | * from this set, the annotated element is implicitly dependent upon the explicitly specified `rule`, which 35 | * corresponds to the `Dependents.SELF` element. 36 | * 37 | * By default, the annotated element is dependent upon the specified `rule` and its `Dependents.PARENTS`, i.e. the 38 | * rule within one level of context information. The parents are included since the most frequent assumption about a 39 | * rule is where it's used in the grammar. 40 | */ 41 | readonly dependents?: Dependents[]; 42 | } 43 | -------------------------------------------------------------------------------- /src/RuleVersion.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:57.7170027-07:00 7 | 8 | import { Parser } from "./Parser"; 9 | import { ParserRuleContext } from "./ParserRuleContext"; 10 | 11 | /** 12 | * 13 | * @author Sam Harwell 14 | */ 15 | export function RuleVersion(version: number) { 16 | 17 | return (target: Parser, propertyKey: PropertyKey, propertyDescriptor: TypedPropertyDescriptor<(...args: any[]) => T>) => { 18 | // intentionally empty 19 | }; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/TokenFactory.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:57.8783640-07:00 7 | 8 | import { CharStream } from "./CharStream"; 9 | import { Token } from "./Token"; 10 | import { TokenSource } from "./TokenSource"; 11 | 12 | /** The default mechanism for creating tokens. It's used by default in Lexer and 13 | * the error handling strategy (to create missing tokens). Notifying the parser 14 | * of a new factory means that it notifies its token source and error strategy. 15 | */ 16 | export interface TokenFactory { 17 | /** This is the method used to create tokens in the lexer and in the 18 | * error handling strategy. If text!=undefined, than the start and stop positions 19 | * are wiped to -1 in the text override is set in the CommonToken. 20 | */ 21 | //@NotNull 22 | create( 23 | /*@NotNull*/ 24 | source: { source?: TokenSource, stream?: CharStream }, 25 | type: number, 26 | text: string | undefined, 27 | channel: number, 28 | start: number, 29 | stop: number, 30 | line: number, 31 | charPositionInLine: number): Token; 32 | 33 | /** Generically useful */ 34 | //@NotNull 35 | createSimple(type: number, text: string): Token; 36 | } 37 | -------------------------------------------------------------------------------- /src/WritableToken.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:59.7015751-07:00 7 | 8 | import { Token } from "./Token"; 9 | 10 | export interface WritableToken extends Token { 11 | text: string | undefined; 12 | 13 | type: number; 14 | 15 | line: number; 16 | 17 | charPositionInLine: number; 18 | 19 | channel: number; 20 | 21 | tokenIndex: number; 22 | } 23 | -------------------------------------------------------------------------------- /src/atn/ATNDeserializationOptions.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:25.8187912-07:00 7 | 8 | import { NotNull } from "../Decorators"; 9 | 10 | /** 11 | * 12 | * @author Sam Harwell 13 | */ 14 | export class ATNDeserializationOptions { 15 | private static _defaultOptions?: ATNDeserializationOptions; 16 | 17 | private readOnly: boolean = false; 18 | private verifyATN: boolean; 19 | private generateRuleBypassTransitions: boolean; 20 | private optimize: boolean; 21 | 22 | constructor(options?: ATNDeserializationOptions) { 23 | if (options) { 24 | this.verifyATN = options.verifyATN; 25 | this.generateRuleBypassTransitions = options.generateRuleBypassTransitions; 26 | this.optimize = options.optimize; 27 | } else { 28 | this.verifyATN = true; 29 | this.generateRuleBypassTransitions = false; 30 | this.optimize = true; 31 | } 32 | } 33 | 34 | @NotNull 35 | static get defaultOptions(): ATNDeserializationOptions { 36 | if (ATNDeserializationOptions._defaultOptions == null) { 37 | ATNDeserializationOptions._defaultOptions = new ATNDeserializationOptions(); 38 | ATNDeserializationOptions._defaultOptions.makeReadOnly(); 39 | } 40 | 41 | return ATNDeserializationOptions._defaultOptions; 42 | } 43 | 44 | get isReadOnly(): boolean { 45 | return this.readOnly; 46 | } 47 | 48 | public makeReadOnly(): void { 49 | this.readOnly = true; 50 | } 51 | 52 | get isVerifyATN(): boolean { 53 | return this.verifyATN; 54 | } 55 | 56 | set isVerifyATN(verifyATN: boolean) { 57 | this.throwIfReadOnly(); 58 | this.verifyATN = verifyATN; 59 | } 60 | 61 | get isGenerateRuleBypassTransitions(): boolean { 62 | return this.generateRuleBypassTransitions; 63 | } 64 | 65 | set isGenerateRuleBypassTransitions(generateRuleBypassTransitions: boolean) { 66 | this.throwIfReadOnly(); 67 | this.generateRuleBypassTransitions = generateRuleBypassTransitions; 68 | } 69 | 70 | get isOptimize(): boolean { 71 | return this.optimize; 72 | } 73 | 74 | set isOptimize(optimize: boolean) { 75 | this.throwIfReadOnly(); 76 | this.optimize = optimize; 77 | } 78 | 79 | protected throwIfReadOnly(): void { 80 | if (this.isReadOnly) { 81 | throw new Error("The object is read only."); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/atn/ATNSimulator.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.3184311-07:00 7 | 8 | import { ATN } from "./ATN"; 9 | import { ATNConfigSet } from "./ATNConfigSet"; 10 | import { DFAState } from "../dfa/DFAState"; 11 | import { NotNull } from "../Decorators"; 12 | import { PredictionContext } from "./PredictionContext"; 13 | 14 | export abstract class ATNSimulator { 15 | /** Must distinguish between missing edge and edge we know leads nowhere */ 16 | private static _ERROR: DFAState; 17 | @NotNull 18 | static get ERROR(): DFAState { 19 | if (!ATNSimulator._ERROR) { 20 | ATNSimulator._ERROR = new DFAState(new ATNConfigSet()); 21 | ATNSimulator._ERROR.stateNumber = PredictionContext.EMPTY_FULL_STATE_KEY; 22 | } 23 | 24 | return ATNSimulator._ERROR; 25 | } 26 | 27 | @NotNull 28 | public atn: ATN; 29 | 30 | constructor(@NotNull atn: ATN) { 31 | this.atn = atn; 32 | } 33 | 34 | public abstract reset(): void; 35 | 36 | /** 37 | * Clear the DFA cache used by the current instance. Since the DFA cache may 38 | * be shared by multiple ATN simulators, this method may affect the 39 | * performance (but not accuracy) of other parsers which are being used 40 | * concurrently. 41 | * 42 | * @ if the current instance does not 43 | * support clearing the DFA. 44 | * 45 | * @since 4.3 46 | */ 47 | public clearDFA(): void { 48 | this.atn.clearDFA(); 49 | } 50 | } 51 | 52 | export namespace ATNSimulator { 53 | const RULE_VARIANT_DELIMITER: string = "$"; 54 | const RULE_LF_VARIANT_MARKER: string = "$lf$"; 55 | const RULE_NOLF_VARIANT_MARKER: string = "$nolf$"; 56 | } 57 | -------------------------------------------------------------------------------- /src/atn/ATNStateType.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.4734328-07:00 7 | 8 | export enum ATNStateType { 9 | INVALID_TYPE = 0, 10 | BASIC = 1, 11 | RULE_START = 2, 12 | BLOCK_START = 3, 13 | PLUS_BLOCK_START = 4, 14 | STAR_BLOCK_START = 5, 15 | TOKEN_START = 6, 16 | RULE_STOP = 7, 17 | BLOCK_END = 8, 18 | STAR_LOOP_BACK = 9, 19 | STAR_LOOP_ENTRY = 10, 20 | PLUS_LOOP_BACK = 11, 21 | LOOP_END = 12, 22 | } 23 | -------------------------------------------------------------------------------- /src/atn/ATNType.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.6094030-07:00 7 | 8 | /** 9 | * Represents the type of recognizer an ATN applies to. 10 | * 11 | * @author Sam Harwell 12 | */ 13 | export const enum ATNType { 14 | 15 | /** 16 | * A lexer grammar. 17 | */ 18 | LEXER, 19 | 20 | /** 21 | * A parser grammar. 22 | */ 23 | PARSER, 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/atn/AbstractPredicateTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:24.6596177-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { Transition } from "./Transition"; 10 | 11 | /** 12 | * 13 | * @author Sam Harwell 14 | */ 15 | export abstract class AbstractPredicateTransition extends Transition { 16 | 17 | constructor(target: ATNState) { 18 | super(target); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/atn/ActionTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:24.7363448-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { Override, NotNull } from "../Decorators"; 10 | import { Transition } from "./Transition"; 11 | import { TransitionType } from "./TransitionType"; 12 | 13 | export class ActionTransition extends Transition { 14 | public ruleIndex: number; 15 | public actionIndex: number; 16 | public isCtxDependent: boolean; // e.g., $i ref in action 17 | 18 | constructor(@NotNull target: ATNState, ruleIndex: number, actionIndex: number = -1, isCtxDependent: boolean = false) { 19 | super(target); 20 | this.ruleIndex = ruleIndex; 21 | this.actionIndex = actionIndex; 22 | this.isCtxDependent = isCtxDependent; 23 | } 24 | 25 | @Override 26 | get serializationType(): TransitionType { 27 | return TransitionType.ACTION; 28 | } 29 | 30 | @Override 31 | get isEpsilon(): boolean { 32 | return true; // we are to be ignored by analysis 'cept for predicates 33 | } 34 | 35 | @Override 36 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 37 | return false; 38 | } 39 | 40 | @Override 41 | public toString(): string { 42 | return "action_" + this.ruleIndex + ":" + this.actionIndex; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/atn/AtomTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.6769122-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { IntervalSet } from "../misc/IntervalSet"; 10 | import { Override, NotNull } from "../Decorators"; 11 | import { Transition } from "./Transition"; 12 | import { TransitionType } from "./TransitionType"; 13 | 14 | /** TODO: make all transitions sets? no, should remove set edges */ 15 | export class AtomTransition extends Transition { 16 | /** The token type or character value; or, signifies special label. */ 17 | public _label: number; 18 | 19 | constructor(@NotNull target: ATNState, label: number) { 20 | super(target); 21 | this._label = label; 22 | } 23 | 24 | @Override 25 | get serializationType(): TransitionType { 26 | return TransitionType.ATOM; 27 | } 28 | 29 | @Override 30 | @NotNull 31 | get label(): IntervalSet { 32 | return IntervalSet.of(this._label); 33 | } 34 | 35 | @Override 36 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 37 | return this._label === symbol; 38 | } 39 | 40 | @Override 41 | @NotNull 42 | public toString(): string { 43 | return String(this.label); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/atn/BasicBlockStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.7669801-07:00 7 | 8 | import { ATNStateType } from "./ATNStateType"; 9 | import { BlockStartState } from "./BlockStartState"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class BasicBlockStartState extends BlockStartState { 17 | 18 | @Override 19 | get stateType(): ATNStateType { 20 | return ATNStateType.BLOCK_START; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/atn/BasicState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.8389930-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class BasicState extends ATNState { 17 | 18 | @Override 19 | get stateType(): ATNStateType { 20 | return ATNStateType.BASIC; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/atn/BlockEndState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.9125304-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { BlockStartState } from "./BlockStartState"; 11 | import { Override } from "../Decorators"; 12 | 13 | /** Terminal node of a simple `(a|b|c)` block. */ 14 | export class BlockEndState extends ATNState { 15 | // This is always set during ATN deserialization 16 | public startState!: BlockStartState; 17 | 18 | @Override 19 | get stateType(): ATNStateType { 20 | return ATNStateType.BLOCK_END; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/atn/BlockStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:27.9930394-07:00 7 | 8 | import { BlockEndState } from "./BlockEndState"; 9 | import { DecisionState } from "./DecisionState"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** The start of a regular `(...)` block. */ 13 | export abstract class BlockStartState extends DecisionState { 14 | // This is always set during ATN deserialization 15 | public endState!: BlockEndState; 16 | } 17 | -------------------------------------------------------------------------------- /src/atn/CodePointTransitions.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import * as Character from "../misc/Character"; 7 | import { ATNState } from "./ATNState"; 8 | import { AtomTransition } from "./AtomTransition"; 9 | import { IntervalSet } from "../misc/IntervalSet"; 10 | import { RangeTransition } from "./RangeTransition"; 11 | import { SetTransition } from "./SetTransition"; 12 | import { Transition } from "./Transition"; 13 | 14 | /** 15 | * Utility functions to create {@link AtomTransition}, {@link RangeTransition}, 16 | * and {@link SetTransition} appropriately based on the range of the input. 17 | * 18 | * To keep the serialized ATN size small, we only inline atom and 19 | * range transitions for Unicode code points <= U+FFFF. 20 | * 21 | * Whenever we encounter a Unicode code point > U+FFFF, we represent that 22 | * as a set transition (even if it is logically an atom or a range). 23 | */ 24 | 25 | /** 26 | * If {@code codePoint} is <= U+FFFF, returns a new {@link AtomTransition}. 27 | * Otherwise, returns a new {@link SetTransition}. 28 | */ 29 | export function createWithCodePoint(target: ATNState, codePoint: number): Transition { 30 | if (Character.isSupplementaryCodePoint(codePoint)) { 31 | return new SetTransition(target, IntervalSet.of(codePoint)); 32 | } 33 | else { 34 | return new AtomTransition(target, codePoint); 35 | } 36 | } 37 | 38 | /** 39 | * If {@code codePointFrom} and {@code codePointTo} are both 40 | * <= U+FFFF, returns a new {@link RangeTransition}. 41 | * Otherwise, returns a new {@link SetTransition}. 42 | */ 43 | export function createWithCodePointRange(target: ATNState, codePointFrom: number, codePointTo: number): Transition { 44 | if (Character.isSupplementaryCodePoint(codePointFrom) || Character.isSupplementaryCodePoint(codePointTo)) { 45 | return new SetTransition(target, IntervalSet.of(codePointFrom, codePointTo)); 46 | } 47 | else { 48 | return new RangeTransition(target, codePointFrom, codePointTo); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/atn/ConflictInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.0710131-07:00 7 | 8 | import { BitSet } from "../misc/BitSet"; 9 | import { Override } from "../Decorators"; 10 | import * as Utils from "../misc/Utils"; 11 | 12 | /** 13 | * This class stores information about a configuration conflict. 14 | * 15 | * @author Sam Harwell 16 | */ 17 | export class ConflictInfo { 18 | private _conflictedAlts: BitSet; 19 | 20 | private exact: boolean; 21 | 22 | constructor(conflictedAlts: BitSet, exact: boolean) { 23 | this._conflictedAlts = conflictedAlts; 24 | this.exact = exact; 25 | } 26 | 27 | /** 28 | * Gets the set of conflicting alternatives for the configuration set. 29 | */ 30 | get conflictedAlts(): BitSet { 31 | return this._conflictedAlts; 32 | } 33 | 34 | /** 35 | * Gets whether or not the configuration conflict is an exact conflict. 36 | * An exact conflict occurs when the prediction algorithm determines that 37 | * the represented alternatives for a particular configuration set cannot be 38 | * further reduced by consuming additional input. After reaching an exact 39 | * conflict during an SLL prediction, only switch to full-context prediction 40 | * could reduce the set of viable alternatives. In LL prediction, an exact 41 | * conflict indicates a true ambiguity in the input. 42 | * 43 | * For the {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction mode, 44 | * accept states are conflicting but not exact are treated as non-accept 45 | * states. 46 | */ 47 | get isExact(): boolean { 48 | return this.exact; 49 | } 50 | 51 | @Override 52 | public equals(obj: any): boolean { 53 | if (obj === this) { 54 | return true; 55 | } else if (!(obj instanceof ConflictInfo)) { 56 | return false; 57 | } 58 | 59 | return this.isExact === obj.isExact 60 | && Utils.equals(this.conflictedAlts, obj.conflictedAlts); 61 | } 62 | 63 | @Override 64 | public hashCode(): number { 65 | return this.conflictedAlts.hashCode(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/atn/ContextSensitivityInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.1575933-07:00 7 | 8 | import { DecisionEventInfo } from "./DecisionEventInfo"; 9 | import { NotNull } from "../Decorators"; 10 | import { SimulatorState } from "./SimulatorState"; 11 | import { TokenStream } from "../TokenStream"; 12 | 13 | /** 14 | * This class represents profiling event information for a context sensitivity. 15 | * Context sensitivities are decisions where a particular input resulted in an 16 | * SLL conflict, but LL prediction produced a single unique alternative. 17 | * 18 | * In some cases, the unique alternative identified by LL prediction is not 19 | * equal to the minimum represented alternative in the conflicting SLL 20 | * configuration set. Grammars and inputs which result in this scenario are 21 | * unable to use {@link PredictionMode#SLL}, which in turn means they cannot use 22 | * the two-stage parsing strategy to improve parsing performance for that 23 | * input. 24 | * 25 | * @see ParserATNSimulator#reportContextSensitivity 26 | * @see ParserErrorListener#reportContextSensitivity 27 | * 28 | * @since 4.3 29 | */ 30 | export class ContextSensitivityInfo extends DecisionEventInfo { 31 | /** 32 | * Constructs a new instance of the {@link ContextSensitivityInfo} class 33 | * with the specified detailed context sensitivity information. 34 | * 35 | * @param decision The decision number 36 | * @param state The final simulator state containing the unique 37 | * alternative identified by full-context prediction 38 | * @param input The input token stream 39 | * @param startIndex The start index for the current prediction 40 | * @param stopIndex The index at which the context sensitivity was 41 | * identified during full-context prediction 42 | */ 43 | constructor( 44 | decision: number, 45 | @NotNull state: SimulatorState, 46 | @NotNull input: TokenStream, 47 | startIndex: number, 48 | stopIndex: number) { 49 | 50 | super(decision, state, input, startIndex, stopIndex, true); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/atn/DecisionEventInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.2401032-07:00 7 | 8 | import { NotNull } from "../Decorators"; 9 | import { SimulatorState } from "./SimulatorState"; 10 | import { TokenStream } from "../TokenStream"; 11 | 12 | /** 13 | * This is the base class for gathering detailed information about prediction 14 | * events which occur during parsing. 15 | * 16 | * Note that we could record the parser call stack at the time this event 17 | * occurred but in the presence of left recursive rules, the stack is kind of 18 | * meaningless. It's better to look at the individual configurations for their 19 | * individual stacks. Of course that is a {@link PredictionContext} object 20 | * not a parse tree node and so it does not have information about the extent 21 | * (start...stop) of the various subtrees. Examining the stack tops of all 22 | * configurations provide the return states for the rule invocations. 23 | * From there you can get the enclosing rule. 24 | * 25 | * @since 4.3 26 | */ 27 | export class DecisionEventInfo { 28 | /** 29 | * The invoked decision number which this event is related to. 30 | * 31 | * @see ATN#decisionToState 32 | */ 33 | public decision: number; 34 | 35 | /** 36 | * The simulator state containing additional information relevant to the 37 | * prediction state when the current event occurred, or `undefined` if no 38 | * additional information is relevant or available. 39 | */ 40 | public state: SimulatorState | undefined; 41 | 42 | /** 43 | * The input token stream which is being parsed. 44 | */ 45 | @NotNull 46 | public input: TokenStream; 47 | 48 | /** 49 | * The token index in the input stream at which the current prediction was 50 | * originally invoked. 51 | */ 52 | public startIndex: number; 53 | 54 | /** 55 | * The token index in the input stream at which the current event occurred. 56 | */ 57 | public stopIndex: number; 58 | 59 | /** 60 | * `true` if the current event occurred during LL prediction; 61 | * otherwise, `false` if the input occurred during SLL prediction. 62 | */ 63 | public fullCtx: boolean; 64 | 65 | constructor( 66 | decision: number, 67 | state: SimulatorState | undefined, 68 | @NotNull input: TokenStream, 69 | startIndex: number, 70 | stopIndex: number, 71 | fullCtx: boolean) { 72 | 73 | this.decision = decision; 74 | this.fullCtx = fullCtx; 75 | this.stopIndex = stopIndex; 76 | this.input = input; 77 | this.startIndex = startIndex; 78 | this.state = state; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/atn/DecisionState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.4381103-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | 10 | export abstract class DecisionState extends ATNState { 11 | public decision: number = -1; 12 | public nonGreedy: boolean = false; 13 | public sll: boolean = false; 14 | } 15 | -------------------------------------------------------------------------------- /src/atn/EpsilonTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.6283213-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { Override, NotNull } from "../Decorators"; 10 | import { Transition } from "./Transition"; 11 | import { TransitionType } from "./TransitionType"; 12 | 13 | export class EpsilonTransition extends Transition { 14 | 15 | private _outermostPrecedenceReturn: number; 16 | 17 | constructor(@NotNull target: ATNState, outermostPrecedenceReturn: number = -1) { 18 | super(target); 19 | this._outermostPrecedenceReturn = outermostPrecedenceReturn; 20 | } 21 | 22 | /** 23 | * @returns the rule index of a precedence rule for which this transition is 24 | * returning from, where the precedence value is 0; otherwise, -1. 25 | * 26 | * @see ATNConfig.isPrecedenceFilterSuppressed 27 | * @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet, ParserRuleContext, PredictionContextCache) 28 | * @since 4.4.1 29 | */ 30 | get outermostPrecedenceReturn(): number { 31 | return this._outermostPrecedenceReturn; 32 | } 33 | 34 | @Override 35 | get serializationType(): TransitionType { 36 | return TransitionType.EPSILON; 37 | } 38 | 39 | @Override 40 | get isEpsilon(): boolean { 41 | return true; 42 | } 43 | 44 | @Override 45 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 46 | return false; 47 | } 48 | 49 | @Override 50 | @NotNull 51 | public toString(): string { 52 | return "epsilon"; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/atn/ErrorInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.7213647-07:00 7 | 8 | import { DecisionEventInfo } from "./DecisionEventInfo"; 9 | import { NotNull } from "../Decorators"; 10 | import { SimulatorState } from "./SimulatorState"; 11 | import { TokenStream } from "../TokenStream"; 12 | 13 | /** 14 | * This class represents profiling event information for a syntax error 15 | * identified during prediction. Syntax errors occur when the prediction 16 | * algorithm is unable to identify an alternative which would lead to a 17 | * successful parse. 18 | * 19 | * @see Parser#notifyErrorListeners(Token, String, RecognitionException) 20 | * @see ANTLRErrorListener#syntaxError 21 | * 22 | * @since 4.3 23 | */ 24 | export class ErrorInfo extends DecisionEventInfo { 25 | /** 26 | * Constructs a new instance of the {@link ErrorInfo} class with the 27 | * specified detailed syntax error information. 28 | * 29 | * @param decision The decision number 30 | * @param state The final simulator state reached during prediction 31 | * prior to reaching the {@link ATNSimulator#ERROR} state 32 | * @param input The input token stream 33 | * @param startIndex The start index for the current prediction 34 | * @param stopIndex The index at which the syntax error was identified 35 | */ 36 | constructor( 37 | decision: number, 38 | @NotNull state: SimulatorState, 39 | @NotNull input: TokenStream, 40 | startIndex: number, 41 | stopIndex: number) { 42 | 43 | super(decision, state, input, startIndex, stopIndex, state.useContext); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/atn/InvalidState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { ATNState } from "./ATNState"; 7 | import { ATNStateType } from "./ATNStateType"; 8 | import { BasicState } from "./BasicState"; 9 | import { Override } from "../Decorators"; 10 | 11 | /** 12 | * 13 | * @author Sam Harwell 14 | */ 15 | export class InvalidState extends BasicState { 16 | 17 | @Override 18 | get stateType(): ATNStateType { 19 | return ATNStateType.INVALID_TYPE; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/atn/LexerAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:28.7973969-07:00 7 | 8 | import { Equatable } from "../misc/Stubs"; 9 | import { Lexer } from "../Lexer"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | 12 | /** 13 | * Represents a single action which can be executed following the successful 14 | * match of a lexer rule. Lexer actions are used for both embedded action syntax 15 | * and ANTLR 4's new lexer command syntax. 16 | * 17 | * @author Sam Harwell 18 | * @since 4.2 19 | */ 20 | export interface LexerAction extends Equatable { 21 | /** 22 | * Gets the serialization type of the lexer action. 23 | * 24 | * @returns The serialization type of the lexer action. 25 | */ 26 | //@NotNull 27 | readonly actionType: LexerActionType; 28 | 29 | /** 30 | * Gets whether the lexer action is position-dependent. Position-dependent 31 | * actions may have different semantics depending on the {@link CharStream} 32 | * index at the time the action is executed. 33 | * 34 | * Many lexer commands, including `type`, `skip`, and 35 | * `more`, do not check the input index during their execution. 36 | * Actions like this are position-independent, and may be stored more 37 | * efficiently as part of the `ATNConfig.lexerActionExecutor`. 38 | * 39 | * @returns `true` if the lexer action semantics can be affected by the 40 | * position of the input {@link CharStream} at the time it is executed; 41 | * otherwise, `false`. 42 | */ 43 | readonly isPositionDependent: boolean; 44 | 45 | /** 46 | * Execute the lexer action in the context of the specified {@link Lexer}. 47 | * 48 | * For position-dependent actions, the input stream must already be 49 | * positioned correctly prior to calling this method. 50 | * 51 | * @param lexer The lexer instance. 52 | */ 53 | execute(/*@NotNull*/ lexer: Lexer): void; 54 | } 55 | -------------------------------------------------------------------------------- /src/atn/LexerActionType.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:29.0172086-07:00 7 | 8 | /** 9 | * Represents the serialization type of a {@link LexerAction}. 10 | * 11 | * @author Sam Harwell 12 | * @since 4.2 13 | */ 14 | export const enum LexerActionType { 15 | /** 16 | * The type of a {@link LexerChannelAction} action. 17 | */ 18 | CHANNEL, 19 | /** 20 | * The type of a {@link LexerCustomAction} action. 21 | */ 22 | CUSTOM, 23 | /** 24 | * The type of a {@link LexerModeAction} action. 25 | */ 26 | MODE, 27 | /** 28 | * The type of a {@link LexerMoreAction} action. 29 | */ 30 | MORE, 31 | /** 32 | * The type of a {@link LexerPopModeAction} action. 33 | */ 34 | POP_MODE, 35 | /** 36 | * The type of a {@link LexerPushModeAction} action. 37 | */ 38 | PUSH_MODE, 39 | /** 40 | * The type of a {@link LexerSkipAction} action. 41 | */ 42 | SKIP, 43 | /** 44 | * The type of a {@link LexerTypeAction} action. 45 | */ 46 | TYPE, 47 | } 48 | -------------------------------------------------------------------------------- /src/atn/LexerChannelAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:29.5634388-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `channel` lexer action by calling 16 | * {@link Lexer#setChannel} with the assigned channel. 17 | * 18 | * @author Sam Harwell 19 | * @since 4.2 20 | */ 21 | export class LexerChannelAction implements LexerAction { 22 | private readonly _channel: number; 23 | 24 | /** 25 | * Constructs a new `channel` action with the specified channel value. 26 | * @param channel The channel value to pass to {@link Lexer#setChannel}. 27 | */ 28 | constructor(channel: number) { 29 | this._channel = channel; 30 | } 31 | 32 | /** 33 | * Gets the channel to use for the {@link Token} created by the lexer. 34 | * 35 | * @returns The channel to use for the {@link Token} created by the lexer. 36 | */ 37 | get channel(): number { 38 | return this._channel; 39 | } 40 | 41 | /** 42 | * {@inheritDoc} 43 | * @returns This method returns {@link LexerActionType#CHANNEL}. 44 | */ 45 | @Override 46 | get actionType(): LexerActionType { 47 | return LexerActionType.CHANNEL; 48 | } 49 | 50 | /** 51 | * {@inheritDoc} 52 | * @returns This method returns `false`. 53 | */ 54 | @Override 55 | get isPositionDependent(): boolean { 56 | return false; 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | * 62 | * This action is implemented by calling {@link Lexer#setChannel} with the 63 | * value provided by {@link #getChannel}. 64 | */ 65 | @Override 66 | public execute(@NotNull lexer: Lexer): void { 67 | lexer.channel = this._channel; 68 | } 69 | 70 | @Override 71 | public hashCode(): number { 72 | let hash: number = MurmurHash.initialize(); 73 | hash = MurmurHash.update(hash, this.actionType); 74 | hash = MurmurHash.update(hash, this._channel); 75 | return MurmurHash.finish(hash, 2); 76 | } 77 | 78 | @Override 79 | public equals(obj: any): boolean { 80 | if (obj === this) { 81 | return true; 82 | } else if (!(obj instanceof LexerChannelAction)) { 83 | return false; 84 | } 85 | 86 | return this._channel === obj._channel; 87 | } 88 | 89 | @Override 90 | public toString(): string { 91 | return `channel(${this._channel})`; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/atn/LexerModeAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:29.8653427-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `mode` lexer action by calling {@link Lexer#mode} with 16 | * the assigned mode. 17 | * 18 | * @author Sam Harwell 19 | * @since 4.2 20 | */ 21 | export class LexerModeAction implements LexerAction { 22 | private readonly _mode: number; 23 | 24 | /** 25 | * Constructs a new `mode` action with the specified mode value. 26 | * @param mode The mode value to pass to {@link Lexer#mode}. 27 | */ 28 | constructor(mode: number) { 29 | this._mode = mode; 30 | } 31 | 32 | /** 33 | * Get the lexer mode this action should transition the lexer to. 34 | * 35 | * @returns The lexer mode for this `mode` command. 36 | */ 37 | get mode(): number { 38 | return this._mode; 39 | } 40 | 41 | /** 42 | * {@inheritDoc} 43 | * @returns This method returns {@link LexerActionType#MODE}. 44 | */ 45 | @Override 46 | get actionType(): LexerActionType { 47 | return LexerActionType.MODE; 48 | } 49 | 50 | /** 51 | * {@inheritDoc} 52 | * @returns This method returns `false`. 53 | */ 54 | @Override 55 | get isPositionDependent(): boolean { 56 | return false; 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | * 62 | * This action is implemented by calling {@link Lexer#mode} with the 63 | * value provided by {@link #getMode}. 64 | */ 65 | @Override 66 | public execute(@NotNull lexer: Lexer): void { 67 | lexer.mode(this._mode); 68 | } 69 | 70 | @Override 71 | public hashCode(): number { 72 | let hash: number = MurmurHash.initialize(); 73 | hash = MurmurHash.update(hash, this.actionType); 74 | hash = MurmurHash.update(hash, this._mode); 75 | return MurmurHash.finish(hash, 2); 76 | } 77 | 78 | @Override 79 | public equals(obj: any): boolean { 80 | if (obj === this) { 81 | return true; 82 | } else if (!(obj instanceof LexerModeAction)) { 83 | return false; 84 | } 85 | 86 | return this._mode === obj._mode; 87 | } 88 | 89 | @Override 90 | public toString(): string { 91 | return `mode(${this._mode})`; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/atn/LexerMoreAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:29.9613221-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `more` lexer action by calling {@link Lexer#more}. 16 | * 17 | * The `more` command does not have any parameters, so this action is 18 | * implemented as a singleton instance exposed by {@link #INSTANCE}. 19 | * 20 | * @author Sam Harwell 21 | * @since 4.2 22 | */ 23 | export class LexerMoreAction implements LexerAction { 24 | /** 25 | * Constructs the singleton instance of the lexer `more` command. 26 | */ 27 | constructor() { 28 | // intentionally empty 29 | } 30 | 31 | /** 32 | * {@inheritDoc} 33 | * @returns This method returns {@link LexerActionType#MORE}. 34 | */ 35 | @Override 36 | get actionType(): LexerActionType { 37 | return LexerActionType.MORE; 38 | } 39 | 40 | /** 41 | * {@inheritDoc} 42 | * @returns This method returns `false`. 43 | */ 44 | @Override 45 | get isPositionDependent(): boolean { 46 | return false; 47 | } 48 | 49 | /** 50 | * {@inheritDoc} 51 | * 52 | * This action is implemented by calling {@link Lexer#more}. 53 | */ 54 | @Override 55 | public execute(@NotNull lexer: Lexer): void { 56 | lexer.more(); 57 | } 58 | 59 | @Override 60 | public hashCode(): number { 61 | let hash: number = MurmurHash.initialize(); 62 | hash = MurmurHash.update(hash, this.actionType); 63 | return MurmurHash.finish(hash, 1); 64 | } 65 | 66 | @Override 67 | public equals(obj: any): boolean { 68 | return obj === this; 69 | } 70 | 71 | @Override 72 | public toString(): string { 73 | return "more"; 74 | } 75 | } 76 | 77 | export namespace LexerMoreAction { 78 | /** 79 | * Provides a singleton instance of this parameterless lexer action. 80 | */ 81 | export const INSTANCE: LexerMoreAction = new LexerMoreAction(); 82 | } 83 | -------------------------------------------------------------------------------- /src/atn/LexerPopModeAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.0449220-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `popMode` lexer action by calling {@link Lexer#popMode}. 16 | * 17 | * The `popMode` command does not have any parameters, so this action is 18 | * implemented as a singleton instance exposed by {@link #INSTANCE}. 19 | * 20 | * @author Sam Harwell 21 | * @since 4.2 22 | */ 23 | export class LexerPopModeAction implements LexerAction { 24 | /** 25 | * Constructs the singleton instance of the lexer `popMode` command. 26 | */ 27 | constructor() { 28 | // intentionally empty 29 | } 30 | 31 | /** 32 | * {@inheritDoc} 33 | * @returns This method returns {@link LexerActionType#POP_MODE}. 34 | */ 35 | @Override 36 | get actionType(): LexerActionType { 37 | return LexerActionType.POP_MODE; 38 | } 39 | 40 | /** 41 | * {@inheritDoc} 42 | * @returns This method returns `false`. 43 | */ 44 | @Override 45 | get isPositionDependent(): boolean { 46 | return false; 47 | } 48 | 49 | /** 50 | * {@inheritDoc} 51 | * 52 | * This action is implemented by calling {@link Lexer#popMode}. 53 | */ 54 | @Override 55 | public execute(@NotNull lexer: Lexer): void { 56 | lexer.popMode(); 57 | } 58 | 59 | @Override 60 | public hashCode(): number { 61 | let hash: number = MurmurHash.initialize(); 62 | hash = MurmurHash.update(hash, this.actionType); 63 | return MurmurHash.finish(hash, 1); 64 | } 65 | 66 | @Override 67 | public equals(obj: any): boolean { 68 | return obj === this; 69 | } 70 | 71 | @Override 72 | public toString(): string { 73 | return "popMode"; 74 | } 75 | } 76 | 77 | export namespace LexerPopModeAction { 78 | /** 79 | * Provides a singleton instance of this parameterless lexer action. 80 | */ 81 | export const INSTANCE: LexerPopModeAction = new LexerPopModeAction(); 82 | } 83 | -------------------------------------------------------------------------------- /src/atn/LexerPushModeAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.1378801-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `pushMode` lexer action by calling 16 | * {@link Lexer#pushMode} with the assigned mode. 17 | * 18 | * @author Sam Harwell 19 | * @since 4.2 20 | */ 21 | export class LexerPushModeAction implements LexerAction { 22 | private readonly _mode: number; 23 | 24 | /** 25 | * Constructs a new `pushMode` action with the specified mode value. 26 | * @param mode The mode value to pass to {@link Lexer#pushMode}. 27 | */ 28 | constructor(mode: number) { 29 | this._mode = mode; 30 | } 31 | 32 | /** 33 | * Get the lexer mode this action should transition the lexer to. 34 | * 35 | * @returns The lexer mode for this `pushMode` command. 36 | */ 37 | get mode(): number { 38 | return this._mode; 39 | } 40 | 41 | /** 42 | * {@inheritDoc} 43 | * @returns This method returns {@link LexerActionType#PUSH_MODE}. 44 | */ 45 | @Override 46 | get actionType(): LexerActionType { 47 | return LexerActionType.PUSH_MODE; 48 | } 49 | 50 | /** 51 | * {@inheritDoc} 52 | * @returns This method returns `false`. 53 | */ 54 | @Override 55 | get isPositionDependent(): boolean { 56 | return false; 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | * 62 | * This action is implemented by calling {@link Lexer#pushMode} with the 63 | * value provided by {@link #getMode}. 64 | */ 65 | @Override 66 | public execute(@NotNull lexer: Lexer): void { 67 | lexer.pushMode(this._mode); 68 | } 69 | 70 | @Override 71 | public hashCode(): number { 72 | let hash: number = MurmurHash.initialize(); 73 | hash = MurmurHash.update(hash, this.actionType); 74 | hash = MurmurHash.update(hash, this._mode); 75 | return MurmurHash.finish(hash, 2); 76 | } 77 | 78 | @Override 79 | public equals(obj: any): boolean { 80 | if (obj === this) { 81 | return true; 82 | } else if (!(obj instanceof LexerPushModeAction)) { 83 | return false; 84 | } 85 | 86 | return this._mode === obj._mode; 87 | } 88 | 89 | @Override 90 | public toString(): string { 91 | return `pushMode(${this._mode})`; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/atn/LexerSkipAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.2324460-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `skip` lexer action by calling {@link Lexer#skip}. 16 | * 17 | * The `skip` command does not have any parameters, so this action is 18 | * implemented as a singleton instance exposed by {@link #INSTANCE}. 19 | * 20 | * @author Sam Harwell 21 | * @since 4.2 22 | */ 23 | export class LexerSkipAction implements LexerAction { 24 | /** 25 | * Constructs the singleton instance of the lexer `skip` command. 26 | */ 27 | constructor() { 28 | // intentionally empty 29 | } 30 | 31 | /** 32 | * {@inheritDoc} 33 | * @returns This method returns {@link LexerActionType#SKIP}. 34 | */ 35 | @Override 36 | get actionType(): LexerActionType { 37 | return LexerActionType.SKIP; 38 | } 39 | 40 | /** 41 | * {@inheritDoc} 42 | * @returns This method returns `false`. 43 | */ 44 | @Override 45 | get isPositionDependent(): boolean { 46 | return false; 47 | } 48 | 49 | /** 50 | * {@inheritDoc} 51 | * 52 | * This action is implemented by calling {@link Lexer#skip}. 53 | */ 54 | @Override 55 | public execute(@NotNull lexer: Lexer): void { 56 | lexer.skip(); 57 | } 58 | 59 | @Override 60 | public hashCode(): number { 61 | let hash: number = MurmurHash.initialize(); 62 | hash = MurmurHash.update(hash, this.actionType); 63 | return MurmurHash.finish(hash, 1); 64 | } 65 | 66 | @Override 67 | public equals(obj: any): boolean { 68 | return obj === this; 69 | } 70 | 71 | @Override 72 | public toString(): string { 73 | return "skip"; 74 | } 75 | } 76 | 77 | export namespace LexerSkipAction { 78 | /** 79 | * Provides a singleton instance of this parameterless lexer action. 80 | */ 81 | export const INSTANCE: LexerSkipAction = new LexerSkipAction(); 82 | } 83 | -------------------------------------------------------------------------------- /src/atn/LexerTypeAction.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.3204839-07:00 7 | 8 | import { Lexer } from "../Lexer"; 9 | import { LexerAction } from "./LexerAction"; 10 | import { LexerActionType } from "./LexerActionType"; 11 | import { MurmurHash } from "../misc/MurmurHash"; 12 | import { NotNull, Override } from "../Decorators"; 13 | 14 | /** 15 | * Implements the `type` lexer action by setting `Lexer.type` 16 | * with the assigned type. 17 | * 18 | * @author Sam Harwell 19 | * @since 4.2 20 | */ 21 | export class LexerTypeAction implements LexerAction { 22 | private readonly _type: number; 23 | 24 | /** 25 | * Constructs a new `type` action with the specified token type value. 26 | * @param type The type to assign to the token using `Lexer.type`. 27 | */ 28 | constructor(type: number) { 29 | this._type = type; 30 | } 31 | 32 | /** 33 | * Gets the type to assign to a token created by the lexer. 34 | * @returns The type to assign to a token created by the lexer. 35 | */ 36 | get type(): number { 37 | return this._type; 38 | } 39 | 40 | /** 41 | * {@inheritDoc} 42 | * @returns This method returns {@link LexerActionType#TYPE}. 43 | */ 44 | @Override 45 | get actionType(): LexerActionType { 46 | return LexerActionType.TYPE; 47 | } 48 | 49 | /** 50 | * {@inheritDoc} 51 | * @returns This method returns `false`. 52 | */ 53 | @Override 54 | get isPositionDependent(): boolean { 55 | return false; 56 | } 57 | 58 | /** 59 | * {@inheritDoc} 60 | * 61 | * This action is implemented by setting `Lexer.type` with the 62 | * value provided by `type`. 63 | */ 64 | @Override 65 | public execute(@NotNull lexer: Lexer): void { 66 | lexer.type = this._type; 67 | } 68 | 69 | @Override 70 | public hashCode(): number { 71 | let hash: number = MurmurHash.initialize(); 72 | hash = MurmurHash.update(hash, this.actionType); 73 | hash = MurmurHash.update(hash, this._type); 74 | return MurmurHash.finish(hash, 2); 75 | } 76 | 77 | @Override 78 | public equals(obj: any): boolean { 79 | if (obj === this) { 80 | return true; 81 | } else if (!(obj instanceof LexerTypeAction)) { 82 | return false; 83 | } 84 | 85 | return this._type === obj._type; 86 | } 87 | 88 | @Override 89 | public toString(): string { 90 | return `type(${this._type})`; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/atn/LookaheadEventInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.6852565-07:00 7 | 8 | import { DecisionEventInfo } from "./DecisionEventInfo"; 9 | import { NotNull } from "../Decorators"; 10 | import { SimulatorState } from "./SimulatorState"; 11 | import { TokenStream } from "../TokenStream"; 12 | 13 | /** 14 | * This class represents profiling event information for tracking the lookahead 15 | * depth required in order to make a prediction. 16 | * 17 | * @since 4.3 18 | */ 19 | export class LookaheadEventInfo extends DecisionEventInfo { 20 | /** The alternative chosen by adaptivePredict(), not necessarily 21 | * the outermost alt shown for a rule; left-recursive rules have 22 | * user-level alts that differ from the rewritten rule with a (...) block 23 | * and a (..)* loop. 24 | */ 25 | public predictedAlt: number; 26 | 27 | /** 28 | * Constructs a new instance of the {@link LookaheadEventInfo} class with 29 | * the specified detailed lookahead information. 30 | * 31 | * @param decision The decision number 32 | * @param state The final simulator state containing the necessary 33 | * information to determine the result of a prediction, or `undefined` if 34 | * the final state is not available 35 | * @param input The input token stream 36 | * @param startIndex The start index for the current prediction 37 | * @param stopIndex The index at which the prediction was finally made 38 | * @param fullCtx `true` if the current lookahead is part of an LL 39 | * prediction; otherwise, `false` if the current lookahead is part of 40 | * an SLL prediction 41 | */ 42 | constructor( 43 | decision: number, 44 | state: SimulatorState | undefined, 45 | predictedAlt: number, 46 | @NotNull input: TokenStream, 47 | startIndex: number, 48 | stopIndex: number, 49 | fullCtx: boolean) { 50 | 51 | super(decision, state, input, startIndex, stopIndex, fullCtx); 52 | this.predictedAlt = predictedAlt; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/atn/LoopEndState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.7737978-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** Mark the end of a * or + loop. */ 13 | export class LoopEndState extends ATNState { 14 | // This is always set during ATN deserialization 15 | public loopBackState!: ATNState; 16 | 17 | @Override 18 | get stateType(): ATNStateType { 19 | return ATNStateType.LOOP_END; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/atn/NotSetTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.8483617-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { IntervalSet } from "../misc/IntervalSet"; 10 | import { Override, NotNull, Nullable } from "../Decorators"; 11 | import { SetTransition } from "./SetTransition"; 12 | import { Transition } from "./Transition"; 13 | import { TransitionType } from "./TransitionType"; 14 | 15 | export class NotSetTransition extends SetTransition { 16 | constructor(@NotNull target: ATNState, @Nullable set: IntervalSet) { 17 | super(target, set); 18 | } 19 | 20 | @Override 21 | get serializationType(): TransitionType { 22 | return TransitionType.NOT_SET; 23 | } 24 | 25 | @Override 26 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 27 | return symbol >= minVocabSymbol 28 | && symbol <= maxVocabSymbol 29 | && !super.matches(symbol, minVocabSymbol, maxVocabSymbol); 30 | } 31 | 32 | @Override 33 | public toString(): string { 34 | return "~" + super.toString(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/atn/OrderedATNConfigSet.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:30.9444556-07:00 7 | 8 | import { ATNConfig } from "./ATNConfig"; 9 | import { ATNConfigSet } from "./ATNConfigSet"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class OrderedATNConfigSet extends ATNConfigSet { 17 | 18 | constructor(); 19 | constructor(set: ATNConfigSet, readonly: boolean); 20 | constructor(set?: ATNConfigSet, readonly?: boolean) { 21 | if (set != null && readonly != null) { 22 | super(set, readonly); 23 | } else { 24 | super(); 25 | } 26 | } 27 | 28 | @Override 29 | public clone(readonly: boolean): ATNConfigSet { 30 | let copy: OrderedATNConfigSet = new OrderedATNConfigSet(this, readonly); 31 | if (!readonly && this.isReadOnly) { 32 | copy.addAll(this); 33 | } 34 | 35 | return copy; 36 | } 37 | 38 | @Override 39 | protected getKey(e: ATNConfig): { state: number, alt: number } { 40 | // This is a specially crafted key to ensure configurations are only merged if they are equal 41 | return { state: 0, alt: e.hashCode() }; 42 | } 43 | 44 | @Override 45 | protected canMerge(left: ATNConfig, leftKey: { state: number, alt: number }, right: ATNConfig): boolean { 46 | return left.equals(right); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/atn/PlusBlockStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:34.9572142-07:00 7 | 8 | import { ATNStateType } from "./ATNStateType"; 9 | import { BlockStartState } from "./BlockStartState"; 10 | import { Override } from "../Decorators"; 11 | import { PlusLoopbackState } from "./PlusLoopbackState"; 12 | 13 | /** Start of `(A|B|...)+` loop. Technically a decision state, but 14 | * we don't use for code generation; somebody might need it, so I'm defining 15 | * it for completeness. In reality, the {@link PlusLoopbackState} node is the 16 | * real decision-making note for `A+`. 17 | */ 18 | export class PlusBlockStartState extends BlockStartState { 19 | // This is always set during ATN deserialization 20 | public loopBackState!: PlusLoopbackState; 21 | 22 | @Override 23 | get stateType(): ATNStateType { 24 | return ATNStateType.PLUS_BLOCK_START; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/atn/PlusLoopbackState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:35.0257730-07:00 7 | 8 | import { ATNStateType } from "./ATNStateType"; 9 | import { DecisionState } from "./DecisionState"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** Decision state for `A+` and `(A|B)+`. It has two transitions: 13 | * one to the loop back to start of the block and one to exit. 14 | */ 15 | export class PlusLoopbackState extends DecisionState { 16 | 17 | @Override 18 | get stateType(): ATNStateType { 19 | return ATNStateType.PLUS_LOOP_BACK; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/atn/PrecedencePredicateTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:35.0994191-07:00 7 | 8 | import { AbstractPredicateTransition } from "./AbstractPredicateTransition"; 9 | import { ATNState } from "./ATNState"; 10 | import { NotNull, Override } from "../Decorators"; 11 | import { SemanticContext } from "./SemanticContext"; 12 | import { TransitionType } from "./TransitionType"; 13 | 14 | /** 15 | * 16 | * @author Sam Harwell 17 | */ 18 | export class PrecedencePredicateTransition extends AbstractPredicateTransition { 19 | public precedence: number; 20 | 21 | constructor( @NotNull target: ATNState, precedence: number) { 22 | super(target); 23 | this.precedence = precedence; 24 | } 25 | 26 | @Override 27 | get serializationType(): TransitionType { 28 | return TransitionType.PRECEDENCE; 29 | } 30 | 31 | @Override 32 | get isEpsilon(): boolean { 33 | return true; 34 | } 35 | 36 | @Override 37 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 38 | return false; 39 | } 40 | 41 | get predicate(): SemanticContext.PrecedencePredicate { 42 | return new SemanticContext.PrecedencePredicate(this.precedence); 43 | } 44 | 45 | @Override 46 | public toString(): string { 47 | return this.precedence + " >= _p"; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/atn/PredicateEvalInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:35.1914305-07:00 7 | 8 | import { DecisionEventInfo } from "./DecisionEventInfo"; 9 | import { NotNull } from "../Decorators"; 10 | import { SemanticContext } from "./SemanticContext"; 11 | import { SimulatorState } from "./SimulatorState"; 12 | import { TokenStream } from "../TokenStream"; 13 | 14 | /** 15 | * This class represents profiling event information for semantic predicate 16 | * evaluations which occur during prediction. 17 | * 18 | * @see ParserATNSimulator#evalSemanticContext 19 | * 20 | * @since 4.3 21 | */ 22 | export class PredicateEvalInfo extends DecisionEventInfo { 23 | /** 24 | * The semantic context which was evaluated. 25 | */ 26 | public semctx: SemanticContext; 27 | /** 28 | * The alternative number for the decision which is guarded by the semantic 29 | * context {@link #semctx}. Note that other ATN 30 | * configurations may predict the same alternative which are guarded by 31 | * other semantic contexts and/or {@link SemanticContext#NONE}. 32 | */ 33 | public predictedAlt: number; 34 | /** 35 | * The result of evaluating the semantic context {@link #semctx}. 36 | */ 37 | public evalResult: boolean; 38 | 39 | /** 40 | * Constructs a new instance of the {@link PredicateEvalInfo} class with the 41 | * specified detailed predicate evaluation information. 42 | * 43 | * @param state The simulator state 44 | * @param decision The decision number 45 | * @param input The input token stream 46 | * @param startIndex The start index for the current prediction 47 | * @param stopIndex The index at which the predicate evaluation was 48 | * triggered. Note that the input stream may be reset to other positions for 49 | * the actual evaluation of individual predicates. 50 | * @param semctx The semantic context which was evaluated 51 | * @param evalResult The results of evaluating the semantic context 52 | * @param predictedAlt The alternative number for the decision which is 53 | * guarded by the semantic context `semctx`. See {@link #predictedAlt} 54 | * for more information. 55 | * 56 | * @see ParserATNSimulator#evalSemanticContext(SemanticContext, ParserRuleContext, int) 57 | * @see SemanticContext#eval(Recognizer, RuleContext) 58 | */ 59 | constructor( 60 | @NotNull state: SimulatorState, 61 | decision: number, 62 | @NotNull input: TokenStream, 63 | startIndex: number, 64 | stopIndex: number, 65 | @NotNull semctx: SemanticContext, 66 | evalResult: boolean, 67 | predictedAlt: number) { 68 | 69 | super(decision, state, input, startIndex, stopIndex, state.useContext); 70 | this.semctx = semctx; 71 | this.evalResult = evalResult; 72 | this.predictedAlt = predictedAlt; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/atn/PredicateTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:35.2826960-07:00 7 | 8 | import { AbstractPredicateTransition } from "./AbstractPredicateTransition"; 9 | import { ATNState } from "./ATNState"; 10 | import { NotNull, Override } from "../Decorators"; 11 | import { SemanticContext } from "./SemanticContext"; 12 | import { TransitionType } from "./TransitionType"; 13 | 14 | /** TODO: this is old comment: 15 | * A tree of semantic predicates from the grammar AST if label==SEMPRED. 16 | * In the ATN, labels will always be exactly one predicate, but the DFA 17 | * may have to combine a bunch of them as it collects predicates from 18 | * multiple ATN configurations into a single DFA state. 19 | */ 20 | export class PredicateTransition extends AbstractPredicateTransition { 21 | public ruleIndex: number; 22 | public predIndex: number; 23 | public isCtxDependent: boolean; // e.g., $i ref in pred 24 | 25 | constructor(@NotNull target: ATNState, ruleIndex: number, predIndex: number, isCtxDependent: boolean) { 26 | super(target); 27 | this.ruleIndex = ruleIndex; 28 | this.predIndex = predIndex; 29 | this.isCtxDependent = isCtxDependent; 30 | } 31 | 32 | @Override 33 | get serializationType(): TransitionType { 34 | return TransitionType.PREDICATE; 35 | } 36 | 37 | @Override 38 | get isEpsilon(): boolean { return true; } 39 | 40 | @Override 41 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 42 | return false; 43 | } 44 | 45 | get predicate(): SemanticContext.Predicate { 46 | return new SemanticContext.Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent); 47 | } 48 | 49 | @Override 50 | @NotNull 51 | public toString(): string { 52 | return "pred_" + this.ruleIndex + ":" + this.predIndex; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/atn/RangeTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:36.5959980-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { IntervalSet } from "../misc/IntervalSet"; 10 | import { Override, NotNull } from "../Decorators"; 11 | import { Transition } from "./Transition"; 12 | import { TransitionType } from "./TransitionType"; 13 | 14 | export class RangeTransition extends Transition { 15 | public from: number; 16 | public to: number; 17 | 18 | constructor(@NotNull target: ATNState, from: number, to: number) { 19 | super(target); 20 | this.from = from; 21 | this.to = to; 22 | } 23 | 24 | @Override 25 | get serializationType(): TransitionType { 26 | return TransitionType.RANGE; 27 | } 28 | 29 | @Override 30 | @NotNull 31 | get label(): IntervalSet { 32 | return IntervalSet.of(this.from, this.to); 33 | } 34 | 35 | @Override 36 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 37 | return symbol >= this.from && symbol <= this.to; 38 | } 39 | 40 | @Override 41 | @NotNull 42 | public toString(): string { 43 | return "'" + String.fromCodePoint(this.from) + "'..'" + String.fromCodePoint(this.to) + "'"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/atn/RuleStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:36.6806851-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { Override } from "../Decorators"; 11 | import { RuleStopState } from "./RuleStopState"; 12 | 13 | export class RuleStartState extends ATNState { 14 | // This is always set during ATN deserialization 15 | public stopState!: RuleStopState; 16 | public isPrecedenceRule: boolean = false; 17 | public leftFactored: boolean = false; 18 | 19 | @Override 20 | get stateType(): ATNStateType { 21 | return ATNStateType.RULE_START; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/atn/RuleStopState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:36.7513856-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** The last node in the ATN for a rule, unless that rule is the start symbol. 13 | * In that case, there is one transition to EOF. Later, we might encode 14 | * references to all calls to this rule to compute FOLLOW sets for 15 | * error handling. 16 | */ 17 | export class RuleStopState extends ATNState { 18 | 19 | @Override 20 | get nonStopStateNumber(): number { 21 | return -1; 22 | } 23 | 24 | @Override 25 | get stateType(): ATNStateType { 26 | return ATNStateType.RULE_STOP; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/atn/RuleTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:36.8294453-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { Override, NotNull } from "../Decorators"; 10 | import { RuleStartState } from "./RuleStartState"; 11 | import { Transition } from "./Transition"; 12 | import { TransitionType } from "./TransitionType"; 13 | 14 | /** */ 15 | export class RuleTransition extends Transition { 16 | /** Ptr to the rule definition object for this rule ref */ 17 | public ruleIndex: number; // no Rule object at runtime 18 | 19 | public precedence: number; 20 | 21 | /** What node to begin computations following ref to rule */ 22 | @NotNull 23 | public followState: ATNState; 24 | 25 | public tailCall: boolean = false; 26 | public optimizedTailCall: boolean = false; 27 | 28 | constructor(@NotNull ruleStart: RuleStartState, ruleIndex: number, precedence: number, @NotNull followState: ATNState) { 29 | super(ruleStart); 30 | this.ruleIndex = ruleIndex; 31 | this.precedence = precedence; 32 | this.followState = followState; 33 | } 34 | 35 | @Override 36 | get serializationType(): TransitionType { 37 | return TransitionType.RULE; 38 | } 39 | 40 | @Override 41 | get isEpsilon(): boolean { 42 | return true; 43 | } 44 | 45 | @Override 46 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 47 | return false; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/atn/SetTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.3060135-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { IntervalSet } from "../misc/IntervalSet"; 10 | import { Override, NotNull, Nullable } from "../Decorators"; 11 | import { Token } from "../Token"; 12 | import { Transition } from "./Transition"; 13 | import { TransitionType } from "./TransitionType"; 14 | 15 | /** A transition containing a set of values. */ 16 | export class SetTransition extends Transition { 17 | @NotNull 18 | public set: IntervalSet; 19 | 20 | // TODO (sam): should we really allow undefined here? 21 | constructor(@NotNull target: ATNState, @Nullable set: IntervalSet) { 22 | super(target); 23 | if (set == null) { 24 | set = IntervalSet.of(Token.INVALID_TYPE); 25 | } 26 | 27 | this.set = set; 28 | } 29 | 30 | @Override 31 | get serializationType(): TransitionType { 32 | return TransitionType.SET; 33 | } 34 | 35 | @Override 36 | @NotNull 37 | get label(): IntervalSet { 38 | return this.set; 39 | } 40 | 41 | @Override 42 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 43 | return this.set.contains(symbol); 44 | } 45 | 46 | @Override 47 | @NotNull 48 | public toString(): string { 49 | return this.set.toString(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/atn/SimulatorState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.3871984-07:00 7 | 8 | import { DFAState } from "../dfa/DFAState"; 9 | import { NotNull } from "../Decorators"; 10 | import { ParserRuleContext } from "../ParserRuleContext"; 11 | 12 | /** 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class SimulatorState { 17 | public outerContext: ParserRuleContext; 18 | 19 | public s0: DFAState; 20 | 21 | public useContext: boolean; 22 | public remainingOuterContext: ParserRuleContext | undefined; 23 | 24 | constructor(outerContext: ParserRuleContext, @NotNull s0: DFAState, useContext: boolean, remainingOuterContext: ParserRuleContext | undefined) { 25 | this.outerContext = outerContext != null ? outerContext : ParserRuleContext.emptyContext(); 26 | this.s0 = s0; 27 | this.useContext = useContext; 28 | this.remainingOuterContext = remainingOuterContext; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/atn/StarBlockStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.5657409-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { BlockStartState } from "./BlockStartState"; 11 | import { Override } from "../Decorators"; 12 | 13 | /** The block that begins a closure loop. */ 14 | export class StarBlockStartState extends BlockStartState { 15 | 16 | @Override 17 | get stateType(): ATNStateType { 18 | return ATNStateType.STAR_BLOCK_START; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/atn/StarLoopEntryState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.7099201-07:00 7 | 8 | import { ATNStateType } from "./ATNStateType"; 9 | import { BitSet } from "../misc/BitSet"; 10 | import { DecisionState } from "./DecisionState"; 11 | import { Override } from "../Decorators"; 12 | import { StarLoopbackState } from "./StarLoopbackState"; 13 | 14 | export class StarLoopEntryState extends DecisionState { 15 | // This is always set during ATN deserialization 16 | public loopBackState!: StarLoopbackState; 17 | 18 | /** 19 | * Indicates whether this state can benefit from a precedence DFA during SLL 20 | * decision making. 21 | * 22 | * This is a computed property that is calculated during ATN deserialization 23 | * and stored for use in {@link ParserATNSimulator} and 24 | * {@link ParserInterpreter}. 25 | * 26 | * @see `DFA.isPrecedenceDfa` 27 | */ 28 | public precedenceRuleDecision: boolean = false; 29 | 30 | /** 31 | * For precedence decisions, this set marks states *S* which have all 32 | * of the following characteristics: 33 | * 34 | * * One or more invocation sites of the current rule returns to 35 | * *S*. 36 | * * The closure from *S* includes the current decision without 37 | * passing through any rule invocations or stepping out of the current 38 | * rule. 39 | * 40 | * This field is not used when {@link #precedenceRuleDecision} is 41 | * `false`. 42 | */ 43 | public precedenceLoopbackStates: BitSet = new BitSet(); 44 | 45 | @Override 46 | get stateType(): ATNStateType { 47 | return ATNStateType.STAR_LOOP_ENTRY; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/atn/StarLoopbackState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.6368726-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { ATNStateType } from "./ATNStateType"; 10 | import { Override } from "../Decorators"; 11 | import { StarLoopEntryState } from "./StarLoopEntryState"; 12 | 13 | export class StarLoopbackState extends ATNState { 14 | get loopEntryState(): StarLoopEntryState { 15 | return this.transition(0).target as StarLoopEntryState; 16 | } 17 | 18 | @Override 19 | get stateType(): ATNStateType { 20 | return ATNStateType.STAR_LOOP_BACK; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/atn/TokensStartState.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.7814046-07:00 7 | 8 | import { ATNStateType } from "./ATNStateType"; 9 | import { DecisionState } from "./DecisionState"; 10 | import { Override } from "../Decorators"; 11 | 12 | /** The Tokens rule start state linking to each lexer rule start state */ 13 | export class TokensStartState extends DecisionState { 14 | 15 | @Override 16 | get stateType(): ATNStateType { 17 | return ATNStateType.TOKEN_START; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/atn/TransitionType.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.8530496-07:00 7 | 8 | export const enum TransitionType { 9 | // constants for serialization 10 | EPSILON = 1, 11 | RANGE = 2, 12 | RULE = 3, 13 | PREDICATE = 4, // e.g., {isType(input.LT(1))}? 14 | ATOM = 5, 15 | ACTION = 6, 16 | SET = 7, // ~(A|B) or ~atom, wildcard, which convert to next 2 17 | NOT_SET = 8, 18 | WILDCARD = 9, 19 | PRECEDENCE = 10, 20 | } 21 | -------------------------------------------------------------------------------- /src/atn/WildcardTransition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:37.9456839-07:00 7 | 8 | import { ATNState } from "./ATNState"; 9 | import { Override, NotNull } from "../Decorators"; 10 | import { Transition } from "./Transition"; 11 | import { TransitionType } from "./TransitionType"; 12 | 13 | export class WildcardTransition extends Transition { 14 | constructor(@NotNull target: ATNState) { 15 | super(target); 16 | } 17 | 18 | @Override 19 | get serializationType(): TransitionType { 20 | return TransitionType.WILDCARD; 21 | } 22 | 23 | @Override 24 | public matches(symbol: number, minVocabSymbol: number, maxVocabSymbol: number): boolean { 25 | return symbol >= minVocabSymbol && symbol <= maxVocabSymbol; 26 | } 27 | 28 | @Override 29 | @NotNull 30 | public toString(): string { 31 | return "."; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/dfa/AcceptStateInfo.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:38.1172076-07:00 7 | 8 | import { LexerActionExecutor } from "../atn/LexerActionExecutor"; 9 | 10 | /** 11 | * Stores information about a {@link DFAState} which is an accept state under 12 | * some condition. Certain settings, such as 13 | * {@link ParserATNSimulator#getPredictionMode()}, may be used in addition to 14 | * this information to determine whether or not a particular state is an accept 15 | * state. 16 | * 17 | * @author Sam Harwell 18 | */ 19 | export class AcceptStateInfo { 20 | private readonly _prediction: number; 21 | private readonly _lexerActionExecutor?: LexerActionExecutor; 22 | 23 | constructor(prediction: number); 24 | constructor(prediction: number, lexerActionExecutor: LexerActionExecutor | undefined); 25 | constructor(prediction: number, lexerActionExecutor?: LexerActionExecutor) { 26 | this._prediction = prediction; 27 | this._lexerActionExecutor = lexerActionExecutor; 28 | } 29 | 30 | /** 31 | * Gets the prediction made by this accept state. Note that this value 32 | * assumes the predicates, if any, in the {@link DFAState} evaluate to 33 | * `true`. If predicate evaluation is enabled, the final prediction of 34 | * the accept state will be determined by the result of predicate 35 | * evaluation. 36 | */ 37 | get prediction(): number { 38 | return this._prediction; 39 | } 40 | 41 | /** 42 | * Gets the {@link LexerActionExecutor} which can be used to execute actions 43 | * and/or commands after the lexer matches a token. 44 | */ 45 | get lexerActionExecutor(): LexerActionExecutor | undefined { 46 | return this._lexerActionExecutor; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/dfa/LexerDFASerializer.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:39.2167238-07:00 7 | 8 | import { DFA } from "./DFA"; 9 | import { DFASerializer } from "./DFASerializer"; 10 | import { NotNull, Override } from "../Decorators"; 11 | import { VocabularyImpl } from "../VocabularyImpl"; 12 | 13 | export class LexerDFASerializer extends DFASerializer { 14 | constructor( @NotNull dfa: DFA) { 15 | super(dfa, VocabularyImpl.EMPTY_VOCABULARY); 16 | } 17 | 18 | @Override 19 | @NotNull 20 | protected getEdgeLabel(i: number): string { 21 | return "'" + String.fromCodePoint(i) + "'"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/dfa/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./AcceptStateInfo"; 7 | export * from "./DFA"; 8 | export * from "./DFASerializer"; 9 | export * from "./DFAState"; 10 | export * from "./LexerDFASerializer"; 11 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./ANTLRErrorListener"; 7 | export * from "./ANTLRErrorStrategy"; 8 | // export * from "./ANTLRFileStream"; 9 | export * from "./ANTLRInputStream"; 10 | export * from "./BailErrorStrategy"; 11 | export * from "./BufferedTokenStream"; 12 | export * from "./CharStream"; 13 | export * from "./CharStreams"; 14 | export * from "./CodePointBuffer"; 15 | export * from "./CodePointCharStream"; 16 | export * from "./CommonToken"; 17 | export * from "./CommonTokenFactory"; 18 | export * from "./CommonTokenStream"; 19 | export * from "./ConsoleErrorListener"; 20 | export * from "./DefaultErrorStrategy"; 21 | export * from "./Dependents"; 22 | export * from "./DiagnosticErrorListener"; 23 | export * from "./FailedPredicateException"; 24 | export * from "./InputMismatchException"; 25 | export * from "./InterpreterRuleContext"; 26 | export * from "./IntStream"; 27 | export * from "./Lexer"; 28 | export * from "./LexerInterpreter"; 29 | export * from "./LexerNoViableAltException"; 30 | export * from "./ListTokenSource"; 31 | export * from "./NoViableAltException"; 32 | export * from "./Parser"; 33 | export * from "./ParserErrorListener"; 34 | export * from "./ParserInterpreter"; 35 | export * from "./ParserRuleContext"; 36 | export * from "./ProxyErrorListener"; 37 | export * from "./ProxyParserErrorListener"; 38 | export * from "./RecognitionException"; 39 | export * from "./Recognizer"; 40 | export * from "./RuleContext"; 41 | export * from "./RuleContextWithAltNum"; 42 | export * from "./RuleDependency"; 43 | export * from "./RuleVersion"; 44 | export * from "./Token"; 45 | export * from "./TokenFactory"; 46 | export * from "./TokenSource"; 47 | export * from "./TokenStream"; 48 | export * from "./TokenStreamRewriter"; 49 | // export * from "./UnbufferedCharStream"; 50 | // export * from "./UnbufferedTokenStream"; 51 | export * from "./Vocabulary"; 52 | export * from "./VocabularyImpl"; 53 | export * from "./WritableToken"; 54 | -------------------------------------------------------------------------------- /src/misc/Args.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:39.6568608-07:00 7 | 8 | /** 9 | * Validates that an argument is not `null` or `undefined`. 10 | * 11 | * @param parameterName The name of the parameter 12 | * @param value The argument value 13 | * 14 | * @throws `TypeError` if `value` is `null` or `undefined`. 15 | */ 16 | export function notNull(parameterName: string, value: any): void { 17 | if (value == null) { 18 | throw new TypeError(parameterName + " cannot be null or undefined."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/misc/ArrayEqualityComparator.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-03T02:09:42.2127260-07:00 7 | import { EqualityComparator } from "./EqualityComparator"; 8 | import { Override } from "../Decorators"; 9 | import { Equatable } from "./Stubs"; 10 | import { MurmurHash } from "./MurmurHash"; 11 | import { ObjectEqualityComparator } from "./ObjectEqualityComparator"; 12 | 13 | /** 14 | * This default implementation of {@link EqualityComparator} uses object equality 15 | * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. 16 | * 17 | * @author Sam Harwell 18 | */ 19 | export class ArrayEqualityComparator implements EqualityComparator { 20 | public static readonly INSTANCE: ArrayEqualityComparator = new ArrayEqualityComparator(); 21 | 22 | /** 23 | * {@inheritDoc} 24 | * 25 | * This implementation returns 26 | * `obj.`{@link Object#hashCode hashCode()}. 27 | */ 28 | @Override 29 | public hashCode(obj: Equatable[]): number { 30 | if (obj == null) { 31 | return 0; 32 | } 33 | 34 | return MurmurHash.hashCode(obj, 0); 35 | } 36 | 37 | /** 38 | * {@inheritDoc} 39 | * 40 | * This implementation relies on object equality. If both objects are 41 | * `undefined`, this method returns `true`. Otherwise if only 42 | * `a` is `undefined`, this method returns `false`. Otherwise, 43 | * this method returns the result of 44 | * `a.`{@link Object#equals equals}`(b)`. 45 | */ 46 | @Override 47 | public equals(a: Equatable[], b: Equatable[]): boolean { 48 | if (a == null) { 49 | return b == null; 50 | } else if (b == null) { 51 | return false; 52 | } 53 | 54 | if (a.length !== b.length) { 55 | return false; 56 | } 57 | 58 | for (let i = 0; i < a.length; i++) { 59 | if (!ObjectEqualityComparator.INSTANCE.equals(a[i], b[i])) { 60 | return false; 61 | } 62 | } 63 | 64 | return true; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/misc/Arrays.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export namespace Arrays { 7 | /** 8 | * Searches the specified array of numbers for the specified value using the binary search algorithm. The array must 9 | * be sorted prior to making this call. If it is not sorted, the results are unspecified. If the array contains 10 | * multiple elements with the specified value, there is no guarantee which one will be found. 11 | * 12 | * @returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The 13 | * insertion point is defined as the point at which the key would be inserted into the array: the index of the first 14 | * element greater than the key, or array.length if all elements in the array are less than the specified key. Note 15 | * that this guarantees that the return value will be >= 0 if and only if the key is found. 16 | */ 17 | export function binarySearch(array: ArrayLike, key: number, fromIndex?: number, toIndex?: number): number { 18 | return binarySearch0(array, fromIndex !== undefined ? fromIndex : 0, toIndex !== undefined ? toIndex : array.length, key); 19 | } 20 | 21 | function binarySearch0(array: ArrayLike, fromIndex: number, toIndex: number, key: number): number { 22 | let low: number = fromIndex; 23 | let high: number = toIndex - 1; 24 | 25 | while (low <= high) { 26 | let mid: number = (low + high) >>> 1; 27 | let midVal: number = array[mid]; 28 | 29 | if (midVal < key) { 30 | low = mid + 1; 31 | } else if (midVal > key) { 32 | high = mid - 1; 33 | } else { 34 | // key found 35 | return mid; 36 | } 37 | } 38 | 39 | // key not found. 40 | return -(low + 1); 41 | } 42 | 43 | export function toString(array: Iterable) { 44 | let result = "["; 45 | 46 | let first = true; 47 | for (let element of array) { 48 | if (first) { 49 | first = false; 50 | } else { 51 | result += ", "; 52 | } 53 | 54 | if (element === null) { 55 | result += "null"; 56 | } else if (element === undefined) { 57 | result += "undefined"; 58 | } else { 59 | result += element; 60 | } 61 | } 62 | 63 | result += "]"; 64 | return result; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/misc/Character.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export function isHighSurrogate(ch: number): boolean { 7 | return ch >= 0xD800 && ch <= 0xDBFF; 8 | } 9 | 10 | export function isLowSurrogate(ch: number): boolean { 11 | return ch >= 0xDC00 && ch <= 0xDFFF; 12 | } 13 | 14 | export function isSupplementaryCodePoint(ch: number): boolean { 15 | return ch >= 0x10000; 16 | } 17 | -------------------------------------------------------------------------------- /src/misc/DefaultEqualityComparator.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { EqualityComparator } from "./EqualityComparator"; 7 | import { Override } from "../Decorators"; 8 | import { Equatable } from "./Stubs"; 9 | import { MurmurHash } from "./MurmurHash"; 10 | import { ObjectEqualityComparator } from "./ObjectEqualityComparator"; 11 | 12 | /** 13 | * This default implementation of {@link EqualityComparator} uses object equality 14 | * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. 15 | * 16 | * @author Sam Harwell 17 | */ 18 | export class DefaultEqualityComparator implements EqualityComparator { 19 | public static readonly INSTANCE: DefaultEqualityComparator = new DefaultEqualityComparator(); 20 | 21 | /** 22 | * {@inheritDoc} 23 | * 24 | * This implementation returns 25 | * `obj.`{@link Object#hashCode hashCode()}. 26 | */ 27 | @Override 28 | public hashCode(obj: any): number { 29 | if (obj == null) { 30 | return 0; 31 | } else if (typeof obj === "string" || typeof obj === "number") { 32 | return MurmurHash.hashCode([obj]); 33 | } else { 34 | return ObjectEqualityComparator.INSTANCE.hashCode(obj as Equatable); 35 | } 36 | } 37 | 38 | /** 39 | * {@inheritDoc} 40 | * 41 | * This implementation relies on object equality. If both objects are 42 | * `undefined` or `null`, this method returns `true`. Otherwise if only 43 | * `a` is `undefined` or `null`, this method returns `false`. Otherwise, 44 | * this method returns the result of 45 | * `a.`{@link Object#equals equals}`(b)`. 46 | */ 47 | @Override 48 | public equals(a: any, b: any): boolean { 49 | if (a == null) { 50 | return b == null; 51 | } else if (typeof a === "string" || typeof a === "number") { 52 | return a === b; 53 | } else { 54 | return ObjectEqualityComparator.INSTANCE.equals(a as Equatable, b as Equatable); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/misc/DoubleKeyMap.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:39.9974331-07:00 7 | 8 | /** Sometimes we need to map a key to a value but key is two pieces of data. 9 | * This nested hash table saves creating a single key each time we access 10 | * map; avoids mem creation. 11 | */ 12 | export class DoubleKeyMap { 13 | let data: Map> = new LinkedHashMap>(); 14 | 15 | put(k1: Key1, k2: Key2, v: Value): Value { 16 | let data2: Map = data.get(k1); 17 | let prev: Value = null; 18 | if ( data2==null ) { 19 | data2 = new LinkedHashMap(); 20 | data.put(k1, data2); 21 | } 22 | else { 23 | prev = data2.get(k2); 24 | } 25 | data2.put(k2, v); 26 | return prev; 27 | } 28 | 29 | get(k1: Key1, k2: Key2): Value { 30 | let data2: Map = data.get(k1); 31 | if ( data2==null ) return null; 32 | return data2.get(k2); 33 | } 34 | 35 | get(Key1 k1) { return data.get(k1): Map; } 36 | 37 | /** Get all values associated with primary key */ 38 | values(k1: Key1): Collection { 39 | let data2: Map = data.get(k1); 40 | if ( data2==null ) return null; 41 | return data2.values(); 42 | } 43 | 44 | /** get all primary keys */ 45 | keySet(): Set { 46 | return data.keySet(); 47 | } 48 | 49 | /** get all secondary keys associated with a primary key */ 50 | keySet(k1: Key1): Set { 51 | let data2: Map = data.get(k1); 52 | if ( data2==null ) return null; 53 | return data2.keySet(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/misc/EqualityComparator.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-03T02:09:42.0574481-07:00 7 | 8 | /** 9 | * This interface provides an abstract concept of object equality independent of 10 | * {@link Object#equals} (object equality) and the `==` operator 11 | * (reference equality). It can be used to provide algorithm-specific unordered 12 | * comparisons without requiring changes to the object itself. 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export interface EqualityComparator { 17 | 18 | /** 19 | * This method returns a hash code for the specified object. 20 | * 21 | * @param obj The object. 22 | * @returns The hash code for `obj`. 23 | */ 24 | hashCode(obj: T): number; 25 | 26 | /** 27 | * This method tests if two objects are equal. 28 | * 29 | * @param a The first object to compare. 30 | * @param b The second object to compare. 31 | * @returns `true` if `a` equals `b`, otherwise `false`. 32 | */ 33 | equals(a: T, b: T): boolean; 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/misc/IntegerStack.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:40.6647101-07:00 7 | 8 | import { IntegerList } from "./IntegerList"; 9 | 10 | /** 11 | * 12 | * @author Sam Harwell 13 | */ 14 | export class IntegerStack extends IntegerList { 15 | 16 | constructor(arg?: number | IntegerStack) { 17 | super(arg); 18 | } 19 | 20 | public push(value: number): void { 21 | this.add(value); 22 | } 23 | 24 | public pop(): number { 25 | return this.removeAt(this.size - 1); 26 | } 27 | 28 | public peek(): number { 29 | return this.get(this.size - 1); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/misc/LogManager.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:41.8188111-07:00 7 | 8 | export class LogManager { 9 | protected static class Record { 10 | let timestamp: number; 11 | let location: StackTraceElement; 12 | let component: string; 13 | let msg: string; 14 | public Record() { 15 | timestamp = System.currentTimeMillis(); 16 | location = new Throwable().getStackTrace()[0]; 17 | } 18 | 19 | @Override 20 | toString(): string { 21 | let buf: StringBuilder = new StringBuilder(); 22 | buf.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date(timestamp))); 23 | buf.append(" "); 24 | buf.append(component); 25 | buf.append(" "); 26 | buf.append(location.getFileName()); 27 | buf.append(":"); 28 | buf.append(location.getLineNumber()); 29 | buf.append(" "); 30 | buf.append(msg); 31 | return buf.toString(); 32 | } 33 | } 34 | 35 | protected records: List; 36 | 37 | log(@Nullable component: string, msg: string): void { 38 | let r: Record = new Record(); 39 | r.component = component; 40 | r.msg = msg; 41 | if ( records==null ) { 42 | records = new ArrayList(); 43 | } 44 | records.add(r); 45 | } 46 | 47 | log(String msg) { log(null, msg): void; } 48 | 49 | save(filename: string): void { 50 | let fw: FileWriter = new FileWriter(filename); 51 | let bw: BufferedWriter = new BufferedWriter(fw); 52 | try { 53 | bw.write(toString()); 54 | } 55 | finally { 56 | bw.close(); 57 | } 58 | } 59 | 60 | save(): string { 61 | //String dir = System.getProperty("java.io.tmpdir"); 62 | let dir: string = "."; 63 | let defaultFilename: string = 64 | dir + "/antlr-" + 65 | SimpleDateFormat("yyyy-MM-dd-HH.mm.ss").format(new Date()): new + ".log"; 66 | save(defaultFilename); 67 | return defaultFilename; 68 | } 69 | 70 | @Override 71 | toString(): string { 72 | if ( records==null ) return ""; 73 | let nl: string = System.getProperty("line.separator"); 74 | let buf: StringBuilder = new StringBuilder(); 75 | for (let r of records) { 76 | buf.append(r); 77 | buf.append(nl); 78 | } 79 | return buf.toString(); 80 | } 81 | 82 | static main(args: string[]): void { 83 | let mgr: LogManager = new LogManager(); 84 | mgr.log("atn", "test msg"); 85 | mgr.log("dfa", "test msg 2"); 86 | console.log(mgr); 87 | mgr.save(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/misc/MultiMap.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:42.1346951-07:00 7 | 8 | export class MultiMap extends Map { 9 | constructor() { 10 | super(); 11 | } 12 | 13 | public map(key: K, value: V): void { 14 | let elementsForKey = super.get(key); 15 | if (!elementsForKey) { 16 | elementsForKey = [] as V[]; 17 | super.set(key, elementsForKey); 18 | } 19 | elementsForKey.push(value); 20 | } 21 | 22 | public getPairs(): Array<[K, V]> { 23 | let pairs: Array<[K, V]> = []; 24 | this.forEach((values: V[], key: K) => { 25 | values.forEach((v) => { 26 | pairs.push([key, v]); 27 | }); 28 | }); 29 | return pairs; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/misc/ObjectEqualityComparator.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-03T02:09:42.2127260-07:00 7 | import { EqualityComparator } from "./EqualityComparator"; 8 | import { Override } from "../Decorators"; 9 | import { Equatable } from "./Stubs"; 10 | 11 | /** 12 | * This default implementation of {@link EqualityComparator} uses object equality 13 | * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. 14 | * 15 | * @author Sam Harwell 16 | */ 17 | export class ObjectEqualityComparator implements EqualityComparator { 18 | public static readonly INSTANCE: ObjectEqualityComparator = new ObjectEqualityComparator(); 19 | 20 | /** 21 | * {@inheritDoc} 22 | * 23 | * This implementation returns 24 | * `obj.`{@link Object#hashCode hashCode()}. 25 | */ 26 | @Override 27 | public hashCode(obj: Equatable | null | undefined): number { 28 | if (obj == null) { 29 | return 0; 30 | } 31 | 32 | return obj.hashCode(); 33 | } 34 | 35 | /** 36 | * {@inheritDoc} 37 | * 38 | * This implementation relies on object equality. If both objects are 39 | * `undefined` or `null`, this method returns `true`. Otherwise if only 40 | * `a` is `undefined` or `null`, this method returns `false`. Otherwise, 41 | * this method returns the result of 42 | * `a.`{@link Object#equals equals}`(b)`. 43 | */ 44 | @Override 45 | public equals(a: Equatable | null | undefined, b: Equatable | null | undefined): boolean { 46 | if (a == null) { 47 | return b == null; 48 | } 49 | 50 | return a.equals(b); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/misc/ParseCancellationException.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:42.5447085-07:00 7 | 8 | /** 9 | * This exception is thrown to cancel a parsing operation. This exception does 10 | * not extend {@link RecognitionException}, allowing it to bypass the standard 11 | * error recovery mechanisms. {@link BailErrorStrategy} throws this exception in 12 | * response to a parse error. 13 | * 14 | * @author Sam Harwell 15 | */ 16 | export class ParseCancellationException extends Error { 17 | // private static serialVersionUID: number = -3529552099366979683L; 18 | public readonly stack?: string; 19 | 20 | constructor(public cause: Error) { 21 | super(cause.message); 22 | this.stack = cause.stack; 23 | } 24 | 25 | public getCause(): Error { 26 | return this.cause; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/misc/Stubs.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export interface Equatable { 7 | equals(other: any): boolean; 8 | hashCode(): number; 9 | } 10 | 11 | export interface Comparable { 12 | compareTo(o: T): number; 13 | } 14 | 15 | // This has been tweaked to fore implemenations to support either Java or JavaScript collections passed in... 16 | 17 | export interface JavaCollection extends Iterable, Equatable { 18 | add(e: E): boolean; 19 | addAll(collection: Iterable): boolean; 20 | clear(): void; 21 | contains(o: any): boolean; // Shouldn't argument be restricted to E? 22 | containsAll(collection: Iterable): boolean; // Shouldn't argument be restricted to Collection? 23 | readonly isEmpty: boolean; 24 | readonly size: number; 25 | toArray(): E[]; 26 | } 27 | 28 | export interface JavaSet extends JavaCollection { 29 | // Seems like Java's Set doesn't really seem to extend Java's Collection with anything... 30 | 31 | // add(e:E): boolean; 32 | // addAll(collection:Iterable): boolean; 33 | // clear(): void; 34 | // contains(o:any): boolean; // Shouldn't argument be restricted to E? 35 | // containsAll(collection: Iterable) // Shouldn't argument be restricted to E? 36 | // readonly isEmpty: boolean; 37 | // readonly size: number; 38 | // toArray(): E[]; 39 | } 40 | 41 | export interface JavaMap extends Equatable { 42 | clear(): void; 43 | containsKey(key: K): boolean; 44 | get(key: K): V | undefined; 45 | readonly isEmpty: boolean; 46 | put(key: K, value: V): V | undefined; 47 | readonly size: number; 48 | } 49 | -------------------------------------------------------------------------------- /src/misc/UUID.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { Equatable } from "./Stubs"; 7 | import { MurmurHash } from "./MurmurHash"; 8 | 9 | export class UUID implements Equatable { 10 | private readonly data: Uint32Array; 11 | 12 | constructor(mostSigBits: number, moreSigBits: number, lessSigBits: number, leastSigBits: number) { 13 | this.data = new Uint32Array(4); 14 | this.data[0] = mostSigBits; 15 | this.data[1] = moreSigBits; 16 | this.data[2] = lessSigBits; 17 | this.data[3] = leastSigBits; 18 | } 19 | 20 | public static fromString(data: string): UUID { 21 | if (!/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(data)) { 22 | throw new Error("Incorrectly formatted UUID"); 23 | } 24 | 25 | let segments = data.split("-"); 26 | let mostSigBits = parseInt(segments[0], 16); 27 | let moreSigBits = ((parseInt(segments[1], 16) << 16) >>> 0) + parseInt(segments[2], 16); 28 | let lessSigBits = ((parseInt(segments[3], 16) << 16) >>> 0) + parseInt(segments[4].substr(0, 4), 16); 29 | let leastSigBits = parseInt(segments[4].substr(-8), 16); 30 | return new UUID(mostSigBits, moreSigBits, lessSigBits, leastSigBits); 31 | } 32 | 33 | public hashCode(): number { 34 | return MurmurHash.hashCode([this.data[0], this.data[1], this.data[2], this.data[3]]); 35 | } 36 | 37 | public equals(obj: any): boolean { 38 | if (obj === this) { 39 | return true; 40 | } else if (!(obj instanceof UUID)) { 41 | return false; 42 | } 43 | 44 | return this.data[0] === obj.data[0] 45 | && this.data[1] === obj.data[1] 46 | && this.data[2] === obj.data[2] 47 | && this.data[3] === obj.data[3]; 48 | } 49 | 50 | public toString(): string { 51 | return ("00000000" + this.data[0].toString(16)).substr(-8) 52 | + "-" + ("0000" + (this.data[1] >>> 16).toString(16)).substr(-4) 53 | + "-" + ("0000" + this.data[1].toString(16)).substr(-4) 54 | + "-" + ("0000" + (this.data[2] >>> 16).toString(16)).substr(-4) 55 | + "-" + ("0000" + this.data[2].toString(16)).substr(-4) 56 | + ("00000000" + this.data[3].toString(16)).substr(-8); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/misc/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./Array2DHashMap"; 7 | export * from "./ArrayEqualityComparator"; 8 | export * from "./Args"; 9 | export * from "./Array2DHashSet"; 10 | export * from "./Arrays"; 11 | export * from "./BitSet"; 12 | export * from "./Character"; 13 | export * from "./DefaultEqualityComparator"; 14 | // export * from "./DoubleKeyMap"; 15 | export * from "./EqualityComparator"; 16 | // export * from "./FlexibleHashMap"; 17 | export * from "./IntegerList"; 18 | export * from "./IntegerStack"; 19 | export * from "./InterpreterDataReader"; 20 | export * from "./Interval"; 21 | export * from "./IntervalSet"; 22 | export * from "./IntSet"; 23 | // export * from "./LogManager"; 24 | export * from "./MultiMap"; 25 | export * from "./MurmurHash"; 26 | export * from "./ObjectEqualityComparator"; 27 | // export * from "./OrderedHashSet"; 28 | export * from "./ParseCancellationException"; 29 | // export * from "./RuleDependencyChecker"; 30 | // export * from "./RuleDependencyProcessor"; 31 | export * from "./Utils"; 32 | export * from "./UUID"; 33 | -------------------------------------------------------------------------------- /src/tree/ErrorNode.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.4646355-07:00 7 | 8 | import { Override } from "../Decorators"; 9 | import { ParseTreeVisitor } from "./ParseTreeVisitor"; 10 | import { TerminalNode } from "./TerminalNode"; 11 | import { Token } from "../Token"; 12 | 13 | /** Represents a token that was consumed during resynchronization 14 | * rather than during a valid match operation. For example, 15 | * we will create this kind of a node during single token insertion 16 | * and deletion as well as during "consume until error recovery set" 17 | * upon no viable alternative exceptions. 18 | */ 19 | export class ErrorNode extends TerminalNode { 20 | constructor(token: Token) { 21 | super(token); 22 | } 23 | 24 | @Override 25 | public accept(visitor: ParseTreeVisitor): T { 26 | return visitor.visitErrorNode(this); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/tree/ParseTree.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.5349010-07:00 7 | 8 | import { Parser } from "../Parser"; 9 | import { ParseTreeVisitor } from "./ParseTreeVisitor"; 10 | import { RuleContext } from "../RuleContext"; 11 | import { SyntaxTree } from "./SyntaxTree"; 12 | 13 | /** An interface to access the tree of {@link RuleContext} objects created 14 | * during a parse that makes the data structure look like a simple parse tree. 15 | * This node represents both internal nodes, rule invocations, 16 | * and leaf nodes, token matches. 17 | * 18 | * The payload is either a {@link Token} or a {@link RuleContext} object. 19 | */ 20 | export interface ParseTree extends SyntaxTree { 21 | // the following methods narrow the return type; they are not additional methods 22 | //@Override 23 | readonly parent: ParseTree | undefined; 24 | 25 | /** 26 | * Set the parent for this node. 27 | * 28 | * @since 4.7 29 | */ 30 | setParent(parent: RuleContext): void; 31 | 32 | //@Override 33 | getChild(i: number): ParseTree; 34 | 35 | /** The {@link ParseTreeVisitor} needs a double dispatch method. */ 36 | accept(visitor: ParseTreeVisitor): T; 37 | 38 | /** Return the combined text of all leaf nodes. Does not get any 39 | * off-channel tokens (if any) so won't return whitespace and 40 | * comments if they are sent to parser on hidden channel. 41 | */ 42 | readonly text: string; 43 | 44 | /** Specialize toStringTree so that it can print out more information 45 | * based upon the parser. 46 | */ 47 | toStringTree(parser?: Parser): string; 48 | } 49 | -------------------------------------------------------------------------------- /src/tree/ParseTreeListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.6109431-07:00 7 | 8 | import { ErrorNode } from "./ErrorNode"; 9 | import { ParserRuleContext } from "../ParserRuleContext"; 10 | import { TerminalNode } from "./TerminalNode"; 11 | 12 | /** This interface describes the minimal core of methods triggered 13 | * by {@link ParseTreeWalker}. E.g., 14 | * 15 | * ``` 16 | * ParseTreeWalker walker = new ParseTreeWalker(); 17 | * walker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener 18 | * ``` 19 | * 20 | * If you want to trigger events in multiple listeners during a single 21 | * tree walk, you can use the ParseTreeDispatcher object available at 22 | * 23 | * https://github.com/antlr/antlr4/issues/841 24 | */ 25 | export interface ParseTreeListener { 26 | visitTerminal?: (/*@NotNull*/ node: TerminalNode) => void; 27 | visitErrorNode?: (/*@NotNull*/ node: ErrorNode) => void; 28 | enterEveryRule?: (/*@NotNull*/ ctx: ParserRuleContext) => void; 29 | exitEveryRule?: (/*@NotNull*/ ctx: ParserRuleContext) => void; 30 | } 31 | -------------------------------------------------------------------------------- /src/tree/ParseTreeProperty.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.6782223-07:00 7 | 8 | import { ParseTree } from "./ParseTree"; 9 | 10 | /** 11 | * Associate a property with a parse tree node. Useful with parse tree listeners 12 | * that need to associate values with particular tree nodes, kind of like 13 | * specifying a return value for the listener event method that visited a 14 | * particular node. Example: 15 | * 16 | * ``` 17 | * ParseTreeProperty values = new ParseTreeProperty(); 18 | * values.put(tree, 36); 19 | * int x = values.get(tree); 20 | * values.removeFrom(tree); 21 | * ``` 22 | * 23 | * You would make one decl (values here) in the listener and use lots of times 24 | * in your event methods. 25 | */ 26 | export class ParseTreeProperty { 27 | private _symbol: symbol; 28 | 29 | constructor(name: string = "ParseTreeProperty") { 30 | this._symbol = Symbol(name); 31 | } 32 | 33 | public get(node: ParseTree): V { 34 | return (node as any)[this._symbol] as V; 35 | } 36 | 37 | public set(node: ParseTree, value: V): void { 38 | (node as any)[this._symbol] = value; 39 | } 40 | 41 | public removeFrom(node: ParseTree): V { 42 | let result = (node as any)[this._symbol] as V; 43 | delete (node as any)[this._symbol]; 44 | return result; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/tree/ParseTreeVisitor.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.7512217-07:00 7 | 8 | import { ErrorNode } from "./ErrorNode"; 9 | import { ParseTree } from "./ParseTree"; 10 | import { RuleNode } from "./RuleNode"; 11 | import { TerminalNode } from "./TerminalNode"; 12 | 13 | /** 14 | * This interface defines the basic notion of a parse tree visitor. Generated 15 | * visitors implement this interface and the `XVisitor` interface for 16 | * grammar `X`. 17 | * 18 | * @author Sam Harwell 19 | * @param The return type of the visit operation. Use {@link Void} for 20 | * operations with no return type. 21 | */ 22 | export interface ParseTreeVisitor { 23 | 24 | /** 25 | * Visit a parse tree, and return a user-defined result of the operation. 26 | * 27 | * @param tree The {@link ParseTree} to visit. 28 | * @returns The result of visiting the parse tree. 29 | */ 30 | visit(/*@NotNull*/ tree: ParseTree): Result; 31 | 32 | /** 33 | * Visit the children of a node, and return a user-defined result 34 | * of the operation. 35 | * 36 | * @param node The {@link RuleNode} whose children should be visited. 37 | * @returns The result of visiting the children of the node. 38 | */ 39 | visitChildren(/*@NotNull*/ node: RuleNode): Result; 40 | 41 | /** 42 | * Visit a terminal node, and return a user-defined result of the operation. 43 | * 44 | * @param node The {@link TerminalNode} to visit. 45 | * @returns The result of visiting the node. 46 | */ 47 | visitTerminal(/*@NotNull*/ node: TerminalNode): Result; 48 | 49 | /** 50 | * Visit an error node, and return a user-defined result of the operation. 51 | * 52 | * @param node The {@link ErrorNode} to visit. 53 | * @returns The result of visiting the node. 54 | */ 55 | visitErrorNode(/*@NotNull*/ node: ErrorNode): Result; 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/tree/RuleNode.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.9232756-07:00 7 | 8 | import { RuleContext } from "../RuleContext"; 9 | import { ParseTree } from "./ParseTree"; 10 | import { ParseTreeVisitor } from "./ParseTreeVisitor"; 11 | import { Parser } from "../Parser"; 12 | import { Interval } from "../misc/Interval"; 13 | 14 | export abstract class RuleNode implements ParseTree { 15 | public abstract readonly ruleContext: RuleContext; 16 | 17 | //@Override 18 | public abstract readonly parent: RuleNode | undefined; 19 | 20 | public abstract setParent(parent: RuleContext): void; 21 | 22 | public abstract getChild(i: number): ParseTree; 23 | 24 | public abstract accept(visitor: ParseTreeVisitor): T; 25 | 26 | public abstract readonly text: string; 27 | 28 | public abstract toStringTree(parser?: Parser | undefined): string; 29 | 30 | public abstract readonly sourceInterval: Interval; 31 | 32 | public abstract readonly payload: any; 33 | 34 | public abstract readonly childCount: number; 35 | } 36 | -------------------------------------------------------------------------------- /src/tree/SyntaxTree.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:47.9953174-07:00 7 | 8 | import { Tree } from "./Tree"; 9 | import { Interval } from "../misc/Interval"; 10 | 11 | /** A tree that knows about an interval in a token stream 12 | * is some kind of syntax tree. Subinterfaces distinguish 13 | * between parse trees and other kinds of syntax trees we might want to create. 14 | */ 15 | export interface SyntaxTree extends Tree { 16 | /** 17 | * Return an {@link Interval} indicating the index in the 18 | * {@link TokenStream} of the first and last token associated with this 19 | * subtree. If this node is a leaf, then the interval represents a single 20 | * token and has interval i..i for token index i. 21 | * 22 | * An interval of i..i-1 indicates an empty interval at position 23 | * i in the input stream, where 0 <= i <= the size of the input 24 | * token stream. Currently, the code base can only have i=0..n-1 but 25 | * in concept one could have an empty interval after EOF. 26 | * 27 | * If source interval is unknown, this returns {@link Interval#INVALID}. 28 | * 29 | * As a weird special case, the source interval for rules matched after 30 | * EOF is unspecified. 31 | */ 32 | //@NotNull 33 | readonly sourceInterval: Interval; 34 | } 35 | -------------------------------------------------------------------------------- /src/tree/TerminalNode.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:48.1433686-07:00 7 | 8 | import { Interval } from "../misc/Interval"; 9 | import { Override } from "../Decorators"; 10 | import { Parser } from "../Parser"; 11 | import { ParseTree } from "./ParseTree"; 12 | import { ParseTreeVisitor } from "./ParseTreeVisitor"; 13 | import { RuleContext } from "../RuleContext"; 14 | import { RuleNode } from "./RuleNode"; 15 | import { Token } from "../Token"; 16 | 17 | export class TerminalNode implements ParseTree { 18 | public _symbol: Token; 19 | public _parent: RuleNode | undefined; 20 | 21 | constructor(symbol: Token) { 22 | this._symbol = symbol; 23 | } 24 | 25 | @Override 26 | public getChild(i: number): never { 27 | throw new RangeError("Terminal Node has no children."); 28 | } 29 | 30 | get symbol(): Token { 31 | return this._symbol; 32 | } 33 | 34 | @Override 35 | get parent(): RuleNode | undefined { 36 | return this._parent; 37 | } 38 | 39 | @Override 40 | public setParent(parent: RuleContext): void { 41 | this._parent = parent; 42 | } 43 | 44 | @Override 45 | get payload(): Token { 46 | return this._symbol; 47 | } 48 | 49 | @Override 50 | get sourceInterval(): Interval { 51 | let tokenIndex: number = this._symbol.tokenIndex; 52 | return new Interval(tokenIndex, tokenIndex); 53 | } 54 | 55 | @Override 56 | get childCount(): number { 57 | return 0; 58 | } 59 | 60 | @Override 61 | public accept(visitor: ParseTreeVisitor): T { 62 | return visitor.visitTerminal(this); 63 | } 64 | 65 | @Override 66 | get text(): string { 67 | return this._symbol.text || ""; 68 | } 69 | 70 | @Override 71 | public toStringTree(parser?: Parser): string { 72 | return this.toString(); 73 | } 74 | 75 | @Override 76 | public toString(): string { 77 | if (this._symbol.type === Token.EOF) { 78 | return ""; 79 | } 80 | 81 | return this._symbol.text || ""; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/tree/Tree.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-02T21:58:18.5966470-07:00 7 | 8 | /** The basic notion of a tree has a parent, a payload, and a list of children. 9 | * It is the most abstract interface for all the trees used by ANTLR. 10 | */ 11 | export interface Tree { 12 | /** The parent of this node. If the return value is `undefined`, then this 13 | * node is the root of the tree. 14 | */ 15 | readonly parent: Tree | undefined; 16 | 17 | /** 18 | * This method returns whatever object represents the data at this node. For 19 | * example, for parse trees, the payload can be a {@link Token} representing 20 | * a leaf node or a {@link RuleContext} object representing a rule 21 | * invocation. For abstract syntax trees (ASTs), this is a {@link Token} 22 | * object. 23 | */ 24 | readonly payload: { text?: string }; 25 | 26 | /** 27 | * If there are children, get the `i`th value indexed from 0. Throws a `RangeError` if `i` is less than zero, or 28 | * greater than or equal to `childCount`. 29 | */ 30 | getChild(i: number): Tree; 31 | 32 | /** How many children are there? If there is none, then this 33 | * node represents a leaf node. 34 | */ 35 | readonly childCount: number; 36 | 37 | /** Print out a whole tree, not just a node, in LISP format 38 | * `(root child1 .. childN)`. Print just a node if this is a leaf. 39 | */ 40 | toStringTree(): string; 41 | } 42 | -------------------------------------------------------------------------------- /src/tree/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./AbstractParseTreeVisitor"; 7 | export * from "./ErrorNode"; 8 | export * from "./ParseTree"; 9 | export * from "./ParseTreeListener"; 10 | export * from "./ParseTreeProperty"; 11 | export * from "./ParseTreeVisitor"; 12 | export * from "./ParseTreeWalker"; 13 | export * from "./RuleNode"; 14 | export * from "./SyntaxTree"; 15 | export * from "./TerminalNode"; 16 | export * from "./Tree"; 17 | export * from "./Trees"; 18 | -------------------------------------------------------------------------------- /src/tree/pattern/Chunk.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:45.2799060-07:00 7 | 8 | /** 9 | * A chunk is either a token tag, a rule tag, or a span of literal text within a 10 | * tree pattern. 11 | * 12 | * The method {@link ParseTreePatternMatcher#split(String)} returns a list of 13 | * chunks in preparation for creating a token stream by 14 | * {@link ParseTreePatternMatcher#tokenize(String)}. From there, we get a parse 15 | * tree from with {@link ParseTreePatternMatcher#compile(String, int)}. These 16 | * chunks are converted to {@link RuleTagToken}, {@link TokenTagToken}, or the 17 | * regular tokens of the text surrounding the tags. 18 | */ 19 | export abstract class Chunk { 20 | } 21 | -------------------------------------------------------------------------------- /src/tree/pattern/TagChunk.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:46.1670669-07:00 7 | 8 | import { Chunk } from "./Chunk"; 9 | import { NotNull, Override } from "../../Decorators"; 10 | 11 | /** 12 | * Represents a placeholder tag in a tree pattern. A tag can have any of the 13 | * following forms. 14 | * 15 | * * `expr`: An unlabeled placeholder for a parser rule `expr`. 16 | * * `ID`: An unlabeled placeholder for a token of type `ID`. 17 | * * `e:expr`: A labeled placeholder for a parser rule `expr`. 18 | * * `id:ID`: A labeled placeholder for a token of type `ID`. 19 | * 20 | * This class does not perform any validation on the tag or label names aside 21 | * from ensuring that the tag is a defined, non-empty string. 22 | */ 23 | export class TagChunk extends Chunk { 24 | /** 25 | * This is the backing field for `tag`. 26 | */ 27 | private _tag: string; 28 | /** 29 | * This is the backing field for `label`. 30 | */ 31 | private _label?: string; 32 | 33 | /** 34 | * Construct a new instance of {@link TagChunk} using the specified label 35 | * and tag. 36 | * 37 | * @param label The label for the tag. If this is `undefined`, the 38 | * {@link TagChunk} represents an unlabeled tag. 39 | * @param tag The tag, which should be the name of a parser rule or token 40 | * type. 41 | * 42 | * @exception IllegalArgumentException if `tag` is not defined or 43 | * empty. 44 | */ 45 | constructor(tag: string, label?: string) { 46 | super(); 47 | 48 | if (tag == null || tag.length === 0) { 49 | throw new Error("tag cannot be null or empty"); 50 | } 51 | 52 | this._tag = tag; 53 | this._label = label; 54 | } 55 | 56 | /** 57 | * Get the tag for this chunk. 58 | * 59 | * @returns The tag for the chunk. 60 | */ 61 | @NotNull 62 | get tag(): string { 63 | return this._tag; 64 | } 65 | 66 | /** 67 | * Get the label, if any, assigned to this chunk. 68 | * 69 | * @returns The label assigned to this chunk, or `undefined` if no label is 70 | * assigned to the chunk. 71 | */ 72 | get label(): string | undefined { 73 | return this._label; 74 | } 75 | 76 | /** 77 | * This method returns a text representation of the tag chunk. Labeled tags 78 | * are returned in the form `label:tag`, and unlabeled tags are 79 | * returned as just the tag name. 80 | */ 81 | @Override 82 | public toString(): string { 83 | if (this._label != null) { 84 | return this._label + ":" + this._tag; 85 | } 86 | 87 | return this._tag; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/tree/pattern/TextChunk.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:46.2521448-07:00 7 | 8 | import { Chunk } from "./Chunk"; 9 | import { NotNull, Override } from "../../Decorators"; 10 | 11 | /** 12 | * Represents a span of raw text (concrete syntax) between tags in a tree 13 | * pattern string. 14 | */ 15 | export class TextChunk extends Chunk { 16 | /** 17 | * This is the backing field for {@link #getText}. 18 | */ 19 | @NotNull 20 | private _text: string; 21 | 22 | /** 23 | * Constructs a new instance of {@link TextChunk} with the specified text. 24 | * 25 | * @param text The text of this chunk. 26 | * @exception IllegalArgumentException if `text` is not defined. 27 | */ 28 | constructor(@NotNull text: string) { 29 | super(); 30 | 31 | if (text == null) { 32 | throw new Error("text cannot be null"); 33 | } 34 | 35 | this._text = text; 36 | } 37 | 38 | /** 39 | * Gets the raw text of this chunk. 40 | * 41 | * @returns The text of the chunk. 42 | */ 43 | @NotNull 44 | get text(): string { 45 | return this._text; 46 | } 47 | 48 | /** 49 | * {@inheritDoc} 50 | * 51 | * The implementation for {@link TextChunk} returns the result of 52 | * `text` in single quotes. 53 | */ 54 | @Override 55 | public toString(): string { 56 | return "'" + this._text + "'"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/tree/pattern/TokenTagToken.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:26:46.3281988-07:00 7 | 8 | import { CommonToken } from "../../CommonToken"; 9 | import { NotNull, Override } from "../../Decorators"; 10 | 11 | /** 12 | * A {@link Token} object representing a token of a particular type; e.g., 13 | * ``. These tokens are created for {@link TagChunk} chunks where the 14 | * tag corresponds to a lexer rule or token type. 15 | */ 16 | export class TokenTagToken extends CommonToken { 17 | /** 18 | * This is the backing field for `tokenName`. 19 | */ 20 | @NotNull 21 | private _tokenName: string; 22 | /** 23 | * This is the backing field for `label`. 24 | */ 25 | private _label: string | undefined; 26 | 27 | /** 28 | * Constructs a new instance of {@link TokenTagToken} with the specified 29 | * token name, type, and label. 30 | * 31 | * @param tokenName The token name. 32 | * @param type The token type. 33 | * @param label The label associated with the token tag, or `undefined` if 34 | * the token tag is unlabeled. 35 | */ 36 | constructor(@NotNull tokenName: string, type: number, label?: string) { 37 | super(type); 38 | this._tokenName = tokenName; 39 | this._label = label; 40 | } 41 | 42 | /** 43 | * Gets the token name. 44 | * @returns The token name. 45 | */ 46 | @NotNull 47 | get tokenName(): string { 48 | return this._tokenName; 49 | } 50 | 51 | /** 52 | * Gets the label associated with the rule tag. 53 | * 54 | * @returns The name of the label associated with the rule tag, or 55 | * `undefined` if this is an unlabeled rule tag. 56 | */ 57 | get label(): string | undefined { 58 | return this._label; 59 | } 60 | 61 | /** 62 | * {@inheritDoc} 63 | * 64 | * The implementation for {@link TokenTagToken} returns the token tag 65 | * formatted with `<` and `>` delimiters. 66 | */ 67 | @Override 68 | get text(): string { 69 | if (this._label != null) { 70 | return "<" + this._label + ":" + this._tokenName + ">"; 71 | } 72 | 73 | return "<" + this._tokenName + ">"; 74 | } 75 | 76 | /** 77 | * {@inheritDoc} 78 | * 79 | * The implementation for {@link TokenTagToken} returns a string of the form 80 | * `tokenName:type`. 81 | */ 82 | @Override 83 | public toString(): string { 84 | return this._tokenName + ":" + this.type; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/tree/pattern/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./ParseTreeMatch"; 7 | export * from "./ParseTreePattern"; 8 | export * from "./ParseTreePatternMatcher"; 9 | export * from "./RuleTagToken"; 10 | export * from "./TokenTagToken"; 11 | 12 | // The following are "package-private modules" - exported individually but don't need to be part of the public API 13 | // exposed by this file. 14 | // 15 | // export * from "./Chunk"; 16 | // export * from "./TagChunk"; 17 | // export * from "./TextChunk"; 18 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { Override } from "../../Decorators"; 8 | import { ParseTree } from "../ParseTree"; 9 | 10 | export abstract class XPathElement { 11 | protected nodeName: string; 12 | public invert: boolean; 13 | 14 | /** Construct element like `/ID` or `ID` or `/*` etc... 15 | * op is null if just node 16 | */ 17 | constructor(nodeName: string) { 18 | this.nodeName = nodeName; 19 | this.invert = false; 20 | } 21 | 22 | /** 23 | * Given tree rooted at `t` return all nodes matched by this path 24 | * element. 25 | */ 26 | public abstract evaluate(t: ParseTree): ParseTree[]; 27 | 28 | @Override 29 | public toString(): string { 30 | let inv: string = this.invert ? "!" : ""; 31 | let className: string = Object.constructor.name; 32 | return className + "[" + inv + this.nodeName + "]"; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathLexer.g4: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | lexer grammar XPathLexer; 7 | 8 | tokens { TOKEN_REF, RULE_REF } 9 | 10 | /* 11 | path : separator? word (separator word)* EOF ; 12 | 13 | separator 14 | : '/' '!' 15 | | '//' '!' 16 | | '/' 17 | | '//' 18 | ; 19 | 20 | word: TOKEN_REF 21 | | RULE_REF 22 | | STRING 23 | | '*' 24 | ; 25 | */ 26 | 27 | ANYWHERE : '//' ; 28 | ROOT : '/' ; 29 | WILDCARD : '*' ; 30 | BANG : '!' ; 31 | 32 | ID : NameStartChar NameChar* 33 | { 34 | let text = this.text; 35 | if (text.charAt(0) === text.charAt(0).toUpperCase()) { 36 | this.type = XPathLexer.TOKEN_REF; 37 | } else { 38 | this.type = XPathLexer.RULE_REF; 39 | } 40 | } 41 | ; 42 | 43 | fragment 44 | NameChar : [\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nl}\p{Pc}\p{Nd}\p{Mc}\p{Mn}\p{Cf}\u0000-\u0008\u000E-\u001B\u007F-\u009F] 45 | ; 46 | 47 | fragment 48 | NameStartChar 49 | : [\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nl}] 50 | ; 51 | 52 | STRING : '\'' .*? '\'' ; 53 | 54 | //WS : [ \t\r\n]+ -> skip ; 55 | 56 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathLexerErrorListener.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | 8 | import { ANTLRErrorListener } from "../../ANTLRErrorListener"; 9 | import { Override } from "../../Decorators"; 10 | import { Recognizer } from "../../Recognizer"; 11 | import { RecognitionException } from "../../RecognitionException"; 12 | 13 | export class XPathLexerErrorListener implements ANTLRErrorListener { 14 | @Override 15 | public syntaxError( 16 | recognizer: Recognizer, offendingSymbol: T | undefined, 17 | line: number, charPositionInLine: number, msg: string, 18 | e: RecognitionException | undefined): void { 19 | // intentionally empty 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathRuleAnywhereElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { ParserRuleContext } from "../../ParserRuleContext"; 8 | import { Override } from "../../Decorators"; 9 | import { ParseTree } from "../ParseTree"; 10 | import { Trees } from "../Trees"; 11 | import { XPathElement } from "./XPathElement"; 12 | 13 | /** 14 | * Either `ID` at start of path or `...//ID` in middle of path. 15 | */ 16 | export class XPathRuleAnywhereElement extends XPathElement { 17 | protected ruleIndex: number; 18 | constructor(ruleName: string, ruleIndex: number) { 19 | super(ruleName); 20 | this.ruleIndex = ruleIndex; 21 | } 22 | 23 | @Override 24 | public evaluate(t: ParseTree): ParseTree[] { 25 | return Trees.findAllRuleNodes(t, this.ruleIndex); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathRuleElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { ParserRuleContext } from "../../ParserRuleContext"; 8 | import { Override } from "../../Decorators"; 9 | import { ParseTree } from "../ParseTree"; 10 | import { Trees } from "../Trees"; 11 | import { XPathElement } from "./XPathElement"; 12 | 13 | export class XPathRuleElement extends XPathElement { 14 | protected ruleIndex: number; 15 | constructor(ruleName: string, ruleIndex: number) { 16 | super(ruleName); 17 | this.ruleIndex = ruleIndex; 18 | } 19 | 20 | @Override 21 | public evaluate(t: ParseTree): ParseTree[] { 22 | // return all children of t that match nodeName 23 | let nodes: ParseTree[] = []; 24 | for (let c of Trees.getChildren(t)) { 25 | if (c instanceof ParserRuleContext) { 26 | if ((c.ruleIndex === this.ruleIndex && !this.invert) || 27 | (c.ruleIndex !== this.ruleIndex && this.invert)) { 28 | nodes.push(c); 29 | } 30 | } 31 | } 32 | return nodes; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathTokenAnywhereElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { Override } from "../../Decorators"; 8 | import { ParseTree } from "../ParseTree"; 9 | import { Trees } from "../Trees"; 10 | import { XPathElement } from "./XPathElement"; 11 | 12 | export class XPathTokenAnywhereElement extends XPathElement { 13 | protected tokenType: number; 14 | constructor(tokenName: string, tokenType: number) { 15 | super(tokenName); 16 | this.tokenType = tokenType; 17 | } 18 | 19 | @Override 20 | public evaluate(t: ParseTree): ParseTree[] { 21 | return Trees.findAllTokenNodes(t, this.tokenType); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathTokenElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { Override } from "../../Decorators"; 8 | import { ParseTree } from "../ParseTree"; 9 | import { TerminalNode } from "../TerminalNode"; 10 | import { Trees } from "../Trees"; 11 | import { XPathElement } from "./XPathElement"; 12 | 13 | export class XPathTokenElement extends XPathElement { 14 | protected tokenType: number; 15 | constructor(tokenName: string, tokenType: number) { 16 | super(tokenName); 17 | this.tokenType = tokenType; 18 | } 19 | 20 | @Override 21 | public evaluate(t: ParseTree): ParseTree[] { 22 | // return all children of t that match nodeName 23 | let nodes: ParseTree[] = []; 24 | for (let c of Trees.getChildren(t)) { 25 | if (c instanceof TerminalNode) { 26 | if ((c.symbol.type === this.tokenType && !this.invert) || 27 | (c.symbol.type !== this.tokenType && this.invert)) { 28 | nodes.push(c); 29 | } 30 | } 31 | } 32 | return nodes; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathWildcardAnywhereElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { Override } from "../../Decorators"; 8 | import { ParseTree } from "../ParseTree"; 9 | import { TerminalNode } from "../TerminalNode"; 10 | import { Trees } from "../Trees"; 11 | import { XPath } from "./XPath"; 12 | import { XPathElement } from "./XPathElement"; 13 | 14 | export class XPathWildcardAnywhereElement extends XPathElement { 15 | constructor() { 16 | super(XPath.WILDCARD); 17 | } 18 | 19 | @Override 20 | public evaluate(t: ParseTree): ParseTree[] { 21 | if (this.invert) { 22 | // !* is weird but valid (empty) 23 | return []; 24 | } 25 | return Trees.getDescendants(t); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/tree/xpath/XPathWildcardElement.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // CONVERSTION complete, Burt Harris 10/14/2016 7 | import { Override } from "../../Decorators"; 8 | import { ParseTree } from "../ParseTree"; 9 | import { TerminalNode } from "../TerminalNode"; 10 | import { Trees } from "../Trees"; 11 | import { XPath } from "./XPath"; 12 | import { XPathElement } from "./XPathElement"; 13 | 14 | export class XPathWildcardElement extends XPathElement { 15 | constructor() { 16 | super(XPath.WILDCARD); 17 | } 18 | 19 | @Override 20 | public evaluate(t: ParseTree): ParseTree[] { 21 | let kids: ParseTree[] = []; 22 | if (this.invert) { 23 | // !* is weird but valid (empty) 24 | return kids; 25 | } 26 | for (let c of Trees.getChildren(t)) { 27 | kids.push(c); 28 | } 29 | return kids; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/tree/xpath/index.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | export * from "./XPath"; 7 | export * from "./XPathElement"; 8 | export * from "./XPathLexer"; 9 | export * from "./XPathLexerErrorListener"; 10 | export * from "./XPathRuleAnywhereElement"; 11 | export * from "./XPathRuleElement"; 12 | export * from "./XPathTokenAnywhereElement"; 13 | export * from "./XPathTokenElement"; 14 | export * from "./XPathWildcardAnywhereElement"; 15 | export * from "./XPathWildcardElement"; 16 | -------------------------------------------------------------------------------- /target/src/.npmignore: -------------------------------------------------------------------------------- 1 | *.tgz 2 | -------------------------------------------------------------------------------- /target/src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "antlr4ts", 3 | "version": "0.5.0-dev", 4 | "description": "ANTLR 4 runtime for JavaScript written in Typescript", 5 | "main": "index.js", 6 | "scripts": {}, 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/tunnelvisionlabs/antlr4ts.git" 10 | }, 11 | "keywords": [ 12 | "ANTLR4", 13 | "typescript" 14 | ], 15 | "author": "Terence Parr, Sam Harwell, and Burt Harris", 16 | "license": "BSD-3-Clause", 17 | "bugs": { 18 | "url": "https://github.com/tunnelvisionlabs/antlr4ts/issues" 19 | }, 20 | "homepage": "https://github.com/tunnelvisionlabs/antlr4ts#readme", 21 | "devDependencies": {}, 22 | "dependencies": {} 23 | } 24 | -------------------------------------------------------------------------------- /test/TestArray2DHashSet.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import {Equatable} from "../src/misc/Stubs"; 7 | import {Array2DHashSet} from "../src/misc/Array2DHashSet"; 8 | import {MurmurHash} from "../src/misc/MurmurHash"; 9 | import { suite, test } from "@testdeck/mocha"; 10 | import * as assert from "assert"; 11 | 12 | class EquatableTest implements Equatable { 13 | 14 | constructor( public a: string, public b: string ){} 15 | 16 | public equals(o: any) { 17 | if (this === o) { 18 | return true; 19 | } 20 | if (o instanceof EquatableTest) { 21 | return this.a === o.a && this.b === o.b; 22 | } 23 | return false; 24 | } 25 | 26 | public hashCode() { 27 | // this currently generates a Typescript error because strings aren't Equatable 28 | return MurmurHash.hashCode([this.a, this.b], 5280); 29 | } 30 | } 31 | 32 | const alpha = new EquatableTest("alpha", "1"); 33 | const alpha_again = new EquatableTest("alpha", "1"); 34 | const beta = new EquatableTest("beta", "1"); 35 | 36 | describe("EquatableTest", () => { 37 | 38 | it("should respect identity", () => { 39 | assert( alpha.equals(alpha)); 40 | assert( alpha_again.equals(alpha_again)); 41 | assert( beta.equals(beta)); 42 | }); 43 | 44 | it("should compare equality by value", () => { 45 | assert( alpha.equals(alpha_again)); 46 | assert( alpha_again.equals(alpha)); 47 | }); 48 | 49 | it("should detect difference by value", () => { 50 | assert( !alpha.equals(beta)); 51 | }); 52 | 53 | it("should hash identical values the same", () => { 54 | assert.strictEqual(alpha.hashCode(), alpha_again.hashCode()); 55 | }); 56 | 57 | it("should hash different values differently", () => { 58 | assert.notStrictEqual(alpha.hashCode(), beta.hashCode()); 59 | }); 60 | }); 61 | 62 | describe("Array2DHashSet", () => { 63 | let set: Array2DHashSet; 64 | 65 | beforeEach(() => { set = new Array2DHashSet(); }); 66 | 67 | it("shoud count entities", () => { 68 | assert( set.isEmpty ); 69 | assert.strictEqual( set.size, 0 ); 70 | set.add(alpha); 71 | assert( !set.isEmpty); 72 | assert.strictEqual(set.size, 1); 73 | set.add(beta); 74 | assert.strictEqual(set.size, 2); 75 | }); 76 | 77 | it("should check entries by value", () => { 78 | assert(set.isEmpty); 79 | set.add(alpha); 80 | assert(set.contains(alpha), "identity match failed"); 81 | assert(set.contains(alpha_again), "value match failed"); 82 | assert(!set.contains(beta), "value difference ignored"); 83 | }); 84 | }); 85 | 86 | // 87 | // This exercises the @testdesk/mocha package's ability to 88 | // use more object-oriented test structure using decorators. 89 | // 90 | @suite class DecoratorDriven { 91 | @test 92 | public "Comparison by value"() { 93 | assert(alpha.equals(alpha_again)); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /test/TestMurmurHash.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { MurmurHash } from "../src/misc/MurmurHash"; 7 | 8 | import { suite, test } from "@testdeck/mocha"; 9 | 10 | import * as assert from "assert"; 11 | 12 | @suite 13 | export class TestMurmurHash { 14 | 15 | @test 16 | public testMurmurHash_Empty(): void { 17 | assert.strictEqual(0, MurmurHash.hashCode([], 0)); 18 | } 19 | 20 | @test 21 | public testMurmurHash_EmptyWithSeed(): void { 22 | assert.strictEqual(1364076727, MurmurHash.hashCode([], 1)); 23 | } 24 | 25 | @test 26 | public testMurmurHash_Single(): void { 27 | assert.strictEqual(593689054, MurmurHash.hashCode([0], 0)); 28 | } 29 | 30 | @test 31 | public testMurmurHash_SingleWithSeed(): void { 32 | assert.strictEqual(2028806445, MurmurHash.hashCode([0], 1)); 33 | } 34 | 35 | @test 36 | public testMurmurHash_Multiple(): void { 37 | assert.strictEqual(987256456, MurmurHash.hashCode([0, 1], 0)); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /test/TestTokenStream.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { BufferedTokenStream } from "../src/BufferedTokenStream"; 7 | import { CharStreams } from "../src/CharStreams"; 8 | import { Token } from "../src/Token"; 9 | import { XPathLexer } from "../src/tree/xpath/XPathLexer"; 10 | 11 | import { suite, test } from "@testdeck/mocha"; 12 | 13 | import * as assert from "assert"; 14 | 15 | /** 16 | * This class contains tests for specific API functionality in `TokenStream` and derived types. 17 | */ 18 | @suite 19 | export class TestTokenStream { 20 | 21 | /** 22 | * This is a targeted regression test for antlr/antlr4#1584 (`BufferedTokenStream` cannot be reused after EOF). 23 | */ 24 | @test 25 | public testBufferedTokenStreamReuseAfterFill(): void { 26 | let firstInput = CharStreams.fromString("A"); 27 | let tokenStream = new BufferedTokenStream(new XPathLexer(firstInput)); 28 | tokenStream.fill(); 29 | assert.strictEqual(tokenStream.size, 2); 30 | assert.strictEqual(tokenStream.get(0).type, XPathLexer.TOKEN_REF); 31 | assert.strictEqual(tokenStream.get(1).type, Token.EOF); 32 | 33 | let secondInput = CharStreams.fromString("A/"); 34 | tokenStream.tokenSource = new XPathLexer(secondInput); 35 | tokenStream.fill(); 36 | assert.strictEqual(tokenStream.size, 3); 37 | assert.strictEqual(tokenStream.get(0).type, XPathLexer.TOKEN_REF); 38 | assert.strictEqual(tokenStream.get(1).type, XPathLexer.ROOT); 39 | assert.strictEqual(tokenStream.get(2).type, Token.EOF); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /test/runtime/TestGrammar.g4: -------------------------------------------------------------------------------- 1 | grammar TestGrammar; 2 | 3 | compilationUnit 4 | locals [ 5 | symbols: string[] = ["empty"] 6 | ] 7 | : {console.log($symbols);} member* EOF 8 | ; 9 | 10 | member 11 | : 'data' {console.log($compilationUnit::symbols);} 12 | {$compilationUnit::symbols = ["full"];} 13 | ; 14 | 15 | WS : [ \t]+; 16 | -------------------------------------------------------------------------------- /test/runtime/TestReferenceToListLabels/T.g4: -------------------------------------------------------------------------------- 1 | grammar T; 2 | a : b1=b b2+=b* b3+=';' 3 | {console.log($b1.ctx.toStringTree());} 4 | {console.log(($b2).length);} 5 | {console.log(($b3).length);} ; 6 | b : id_=ID val+=INT*; 7 | ID : 'a'..'z'+ ; 8 | INT : '0'..'9'+; 9 | WS : (' '|'\n') -> skip ; -------------------------------------------------------------------------------- /test/runtime/TestReferenceToListLabels/Test.ts: -------------------------------------------------------------------------------- 1 | import "mocha"; 2 | import * as base from "../BaseTest"; 3 | import { TLexer } from "./gen/TLexer"; 4 | import { TParser } from "./gen/TParser"; 5 | 6 | it(`TestReferenceToListLabels.testLabels`, () => { 7 | base.parserTest( { 8 | debug: false, 9 | expectedErrors: ``, 10 | // tslint:disable:no-trailing-whitespace 11 | expectedOutput: `(abc34 abc 34) 12 | 0 13 | 1 14 | `, 15 | input: `abc 34;`, 16 | // tslint:enable:no-trailing-whitespace 17 | lexer: TLexer, 18 | parser: TParser, 19 | parserStartRule: (parser) => parser.a(), 20 | showDFA: false, 21 | testName: `testLabels`, 22 | }); 23 | }); 24 | 25 | -------------------------------------------------------------------------------- /test/runtime/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "../../target/test/runtime", 4 | "sourceMap": true, 5 | "module": "commonjs", 6 | "target": "es2015", 7 | "lib": [ 8 | "es6" 9 | ], 10 | "noImplicitAny": true, 11 | "strictNullChecks": true, 12 | "experimentalDecorators": true, 13 | "declaration": false, 14 | "preserveConstEnums": true, 15 | "typeRoots": [ 16 | "./node_modules/@types" 17 | ], 18 | "types": [ 19 | "node" 20 | ] 21 | }, 22 | "include": [ 23 | "**/*.ts" 24 | ], 25 | "exclude": [ 26 | "node_modules" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /test/tool/ErrorQueue.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:27:01.7710623-07:00 7 | 8 | // import org.stringtemplate.v4.ST; 9 | 10 | export class ErrorQueue implements ANTLRToolListener { 11 | tool: Tool; 12 | infos: List = new ArrayList(); 13 | errors: List = new ArrayList(); 14 | warnings: List = new ArrayList(); 15 | all: List = new ArrayList(); 16 | 17 | constructor() { 18 | this(null); 19 | } 20 | 21 | constructor1(tool: Tool) { 22 | this.tool = tool; 23 | } 24 | 25 | @Override 26 | info(msg: string): void { 27 | infos.add(msg); 28 | } 29 | 30 | @Override 31 | error(msg: ANTLRMessage): void { 32 | errors.add(msg); 33 | all.add(msg); 34 | } 35 | 36 | @Override 37 | warning(msg: ANTLRMessage): void { 38 | warnings.add(msg); 39 | all.add(msg); 40 | } 41 | 42 | error(msg: ToolMessage): void { 43 | errors.add(msg); 44 | all.add(msg); 45 | } 46 | 47 | get size(): number { 48 | return all.size + infos.size; 49 | } 50 | 51 | @Override 52 | toString(): string { 53 | return toString(false); 54 | } 55 | 56 | toString(rendered: boolean): string { 57 | if (!rendered) { 58 | return Utils.join(all.iterator(), "\n"); 59 | } 60 | 61 | if (tool == null) { 62 | throw new IllegalStateException(String.format("No %s instance is available.", Tool.class.getName())); 63 | } 64 | 65 | let buf: StringBuilder = new StringBuilder(); 66 | for (let m of all) { 67 | let st: ST = tool.errMgr.getMessageTemplate(m); 68 | buf.append(st.render()); 69 | buf.append("\n"); 70 | } 71 | 72 | return buf.toString(); 73 | } 74 | 75 | } 76 | 77 | -------------------------------------------------------------------------------- /test/tool/InterpreterTreeTextProvider.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:27:01.8665704-07:00 7 | 8 | export class InterpreterTreeTextProvider implements TreeTextProvider { 9 | ruleNames: List; 10 | constructor(String[] ruleNames) {this.ruleNames = Arrays.asList(ruleNames) ;} 11 | 12 | @Override 13 | getText(node: Tree): string { 14 | if ( node==null ) return "null"; 15 | let nodeText: string = Trees.getNodeText(node, ruleNames); 16 | if ( node instanceof ErrorNode) { 17 | return ""; 18 | } 19 | return nodeText; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX1.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX1; 2 | 3 | s : ID '=' expr ';' ; 4 | expr : ID | INT ; 5 | ID : [a-z]+ ; 6 | INT : [0-9]+ ; 7 | WS : [ \r\n\t]+ -> skip ; 8 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX2.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX2; 2 | 3 | s : ID '=' expr ';' ; 4 | expr : ID | INT ; 5 | ID : [a-z]+ ; 6 | INT : [0-9]+ ; 7 | WS : [ \r\n\t]+ -> channel(HIDDEN) ; 8 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX3.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX3; 2 | 3 | s : ID '=' expr ';' | expr ';' ; 4 | expr : ID | INT ; 5 | ID : [a-z]+ ; 6 | INT : [0-9]+ ; 7 | WS : [ \r\n\t]+ -> skip ; 8 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX4.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX4; 2 | 3 | s : ID '=' ID ';' ; 4 | ID : [a-z]+ ; 5 | WS : [ \r\n\t]+ -> skip ; 6 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX5.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX5; 2 | 3 | s : ID ';' ; 4 | ID : [a-z]+ ; 5 | WS : [ \r\n\t]+ -> skip ; 6 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX6.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX6; 2 | 3 | s : ID ID ';' ; 4 | ID : [a-z]+ ; 5 | WS : [ \r\n\t]+ -> skip ; 6 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX7.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX7; 2 | 3 | s : ID ID ID ';' ; 4 | ID : [a-z]+ ; 5 | WS : [ \r\n\t]+ -> skip ; 6 | -------------------------------------------------------------------------------- /test/tool/ParseTreeMatcherX8.g4: -------------------------------------------------------------------------------- 1 | grammar ParseTreeMatcherX8; 2 | 3 | s : expr ';' 4 | ; 5 | expr: expr '.' ID 6 | | expr '*' expr 7 | | expr '=' expr 8 | | ID 9 | | INT 10 | ; 11 | ID : [a-z]+ ; 12 | INT : [0-9]+ ; 13 | WS : [ \r\n\t]+ -> skip ; 14 | -------------------------------------------------------------------------------- /test/tool/ParserInterpreterForTesting.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:27:02.1495867-07:00 7 | 8 | export class ParserInterpreterForTesting { 9 | public static class DummyParser extends Parser { 10 | _atn: ATN; 11 | 12 | g: Grammar; 13 | public DummyParser(Grammar g, ATN atn, TokenStream input) { 14 | super(input); 15 | this.g = g; 16 | this._atn = atn; 17 | } 18 | 19 | @Override 20 | get grammarFileName(): string { 21 | throw new UnsupportedOperationException("not implemented"); 22 | } 23 | 24 | @Override 25 | get ruleNames(): string[] { 26 | return g.rules.keySet().toArray(new String[g.rules.size]); 27 | } 28 | 29 | @Override 30 | @Deprecated 31 | getTokenNames(): string[] { 32 | return g.getTokenNames(); 33 | } 34 | 35 | @Override 36 | get atn(): ATN { 37 | return _atn; 38 | } 39 | } 40 | 41 | protected g: Grammar; 42 | protected atnSimulator: ParserATNSimulator; 43 | protected input: TokenStream; 44 | 45 | constructor(@NotNull g: Grammar) { 46 | this.g = g; 47 | } 48 | 49 | constructor1(@NotNull g: Grammar, @NotNull input: TokenStream) { 50 | let antlr: Tool = new Tool(); 51 | antlr.process(g,false); 52 | atnSimulator = new ParserATNSimulator(new DummyParser(g, g.atn, input), g.atn); 53 | } 54 | 55 | adaptivePredict(@NotNull input: TokenStream, decision: number, 56 | @Nullable outerContext: ParserRuleContext): number 57 | { 58 | return atnSimulator.adaptivePredict(input, decision, outerContext); 59 | } 60 | 61 | matchATN(@NotNull input: TokenStream, 62 | @NotNull startState: ATNState): number 63 | { 64 | if (startState.numberOfTransitions == 1) { 65 | return 1; 66 | } 67 | else if (startState instanceof DecisionState) { 68 | return atnSimulator.adaptivePredict(input, ((DecisionState)startState).decision, null, false); 69 | } 70 | else if (startState.numberOfTransitions > 0) { 71 | return 1; 72 | } 73 | else { 74 | return -1; 75 | } 76 | } 77 | 78 | getATNSimulator(): ParserATNSimulator { 79 | return atnSimulator; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /test/tool/RewriterLexer1.g4: -------------------------------------------------------------------------------- 1 | lexer grammar RewriterLexer1; 2 | 3 | A : 'a'; 4 | B : 'b'; 5 | C : 'c'; 6 | -------------------------------------------------------------------------------- /test/tool/RewriterLexer2.g4: -------------------------------------------------------------------------------- 1 | lexer grammar RewriterLexer2; 2 | 3 | ID : 'a'..'z'+; 4 | INT : '0'..'9'+; 5 | SEMI : ';'; 6 | MUL : '*'; 7 | ASSIGN : '='; 8 | WS : ' '+; 9 | -------------------------------------------------------------------------------- /test/tool/RewriterLexer3.g4: -------------------------------------------------------------------------------- 1 | lexer grammar RewriterLexer3; 2 | 3 | ID : 'a'..'z'+; 4 | INT : '0'..'9'+; 5 | SEMI : ';'; 6 | ASSIGN : '='; 7 | PLUS : '+'; 8 | MULT : '*'; 9 | WS : ' '+; 10 | -------------------------------------------------------------------------------- /test/tool/TestDollarParser.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:27:07.8604627-07:00 7 | 8 | // import org.junit.Test; 9 | 10 | // import static org.junit.Assert.assertNull; 11 | // import static org.junit.Assert.assertTrue; 12 | 13 | export class TestDollarParser extends BaseTest { 14 | 15 | @Test 16 | testSimpleCall(): void { 17 | let grammar: string = "grammar T;\n" + 18 | "a : ID { System.out.println( $parser.sourceName ); }\n" + 19 | " ;\n" + 20 | "ID : 'a'..'z'+ ;\n"; 21 | let found: string = execParser("T.g4", grammar, "TParser", "TLexer", "a", "x", true); 22 | assertTrue(found.indexOf(this.getClass().getSimpleName())>=0); 23 | assertNull(this.stderrDuringParse); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /test/tool/TestIntegerList.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { IntegerList } from "../../src/misc/IntegerList"; 7 | 8 | import { suite, test } from "@testdeck/mocha"; 9 | import * as assert from "assert"; 10 | 11 | @suite 12 | export class TestIntegerList { 13 | 14 | @test 15 | public emptyListToEmptyCharArray(): void { 16 | let l: IntegerList = new IntegerList(); 17 | assert.deepStrictEqual(new Uint16Array(0), l.toCharArray()); 18 | } 19 | 20 | @test 21 | public negativeIntegerToCharArrayThrows(): void { 22 | let l: IntegerList = new IntegerList(); 23 | l.add(-42); 24 | assert.throws(() => l.toCharArray(), RangeError); 25 | } 26 | 27 | @test 28 | public surrogateRangeIntegerToCharArray(): void { 29 | let l: IntegerList = new IntegerList(); 30 | // Java allows dangling surrogates, so (currently) we do 31 | // as well. We could change this if desired. 32 | l.add(0xDC00); 33 | let expected = new Uint16Array([0xDC00]); 34 | assert.deepStrictEqual(expected, l.toCharArray()); 35 | } 36 | 37 | @test 38 | public tooLargeIntegerToCharArrayThrows(): void { 39 | let l: IntegerList = new IntegerList(); 40 | l.add(0x110000); 41 | assert.throws(() => l.toCharArray(), RangeError); 42 | } 43 | 44 | @test 45 | public unicodeBMPIntegerListToCharArray(): void { 46 | let l: IntegerList = new IntegerList(); 47 | l.add(0x35); 48 | l.add(0x4E94); 49 | l.add(0xFF15); 50 | let expected = new Uint16Array([0x35, 0x4E94, 0xFF15]); 51 | assert.deepStrictEqual(expected, l.toCharArray()); 52 | } 53 | 54 | @test 55 | public unicodeSMPIntegerListToCharArray(): void { 56 | let l: IntegerList = new IntegerList(); 57 | l.add(0x104A5); 58 | l.add(0x116C5); 59 | l.add(0x1D7FB); 60 | let expected = new Uint16Array([0xD801, 0xDCA5, 0xD805, 0xDEC5, 0xD835, 0xDFFB]); 61 | assert.deepStrictEqual(expected, l.toCharArray()); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /test/tool/TestParseErrors.tssoon: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | // ConvertTo-TS run at 2016-10-04T11:27:14.1522670-07:00 7 | 8 | // import org.junit.Test; 9 | 10 | // import static org.junit.Assert.*; 11 | 12 | /** test runtime parse errors */ 13 | @SuppressWarnings("unused") 14 | export class TestParseErrors extends BaseTest { 15 | /** 16 | * Regression test for "Ambiguity at k=1 prevents full context parsing". 17 | * https://github.com/antlr/antlr4/issues/44 18 | */ 19 | @Test 20 | testConflictingAltAnalysis(): void { 21 | let grammar: string = 22 | "grammar T;\n" + 23 | "ss : s s EOF;\n" + 24 | "s : | x;\n" + 25 | "x : 'a' 'b';\n" + 26 | ""; 27 | let result: string = execParser("T.g", grammar, "TParser", "TLexer", "ss", "abab", true); 28 | let expecting: string = ""; 29 | assertEquals(expecting, result); 30 | assertEquals( 31 | "line 1:4 reportAttemptingFullContext d=0 (s), input='ab'\n" + 32 | "line 1:2 reportContextSensitivity d=0 (s), input='a'\n", 33 | this.stderrDuringParse); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /test/tool/TestVocabulary.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | import { Token } from "../../src/Token"; 7 | import { Vocabulary } from "../../src/Vocabulary"; 8 | import { VocabularyImpl } from "../../src/VocabularyImpl"; 9 | 10 | import * as assert from "assert"; 11 | import { suite, test as Test, skip as Ignore } from "@testdeck/mocha"; 12 | 13 | /** 14 | * 15 | * @author Sam Harwell 16 | */ 17 | @suite 18 | export class TestVocabulary { 19 | 20 | @Test public testEmptyVocabulary(): void { 21 | assert.notStrictEqual(VocabularyImpl.EMPTY_VOCABULARY, undefined); 22 | assert.strictEqual("EOF", VocabularyImpl.EMPTY_VOCABULARY.getSymbolicName(Token.EOF)); 23 | assert.strictEqual("0", VocabularyImpl.EMPTY_VOCABULARY.getDisplayName(Token.INVALID_TYPE)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /test/tool/TestXPath.g4: -------------------------------------------------------------------------------- 1 | grammar TestXPath; 2 | 3 | prog: func+ ; 4 | func: 'def' ID '(' arg (',' arg)* ')' body ; 5 | body: '{' stat+ '}' ; 6 | arg : ID ; 7 | stat: expr ';' # printExpr 8 | | ID '=' expr ';' # assign 9 | | 'return' expr ';' # ret 10 | | ';' # blank 11 | ; 12 | expr: expr ('*'|'/') expr # MulDiv 13 | | expr ('+'|'-') expr # AddSub 14 | | primary # prim 15 | ; 16 | primary 17 | : INT # int 18 | | ID # id 19 | | '(' expr ')' # parens 20 | ; 21 | 22 | MUL : '*' ; // assigns token name to '*' used above in grammar 23 | DIV : '/' ; 24 | ADD : '+' ; 25 | SUB : '-' ; 26 | RETURN : 'return' ; 27 | ID : [a-zA-Z]+ ; // match identifiers 28 | INT : [0-9]+ ; // match integers 29 | NEWLINE:'\r'? '\n' -> skip; // return newlines to parser (is end-statement signal) 30 | WS : [ \t]+ -> skip ; // toss out whitespace 31 | -------------------------------------------------------------------------------- /tool/LICENSE: -------------------------------------------------------------------------------- 1 | [The "BSD license"] 2 | Copyright (c) 2016 The ANTLR Project 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions 7 | are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 2. Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in the 13 | documentation and/or other materials provided with the distribution. 14 | 3. Neither the name of the copyright holder nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 19 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 20 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 22 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 23 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 27 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /tool/README.md: -------------------------------------------------------------------------------- 1 | # antlr4ts-cli -- TypeScript/JavaScript target code generator for ANTLR 4 2 | 3 | > Copyright 2016 The ANTLR Project. All rights reserved. 4 | > 5 | > Licensed under the BSD-3-Clause license. See [LICENSE](./LICENSE) file in the project root for license information. 6 | 7 |
Stability 1 - Experimental. :warning:
8 | This feature was introduced recently, and may change or be removed in the future.
9 | 10 | #Installation 11 | 12 | `npm install -g antlr4ts-cli` 13 | 14 | You may also install a copy of this local to your package using this command: 15 | 16 | `npm install --save-dev antlr4ts-cli` 17 | 18 | 19 | This is a NPM wrapper of a ANTLR 4 code generation tool for TypeScript. The actual tool is written in Java, so you will need 20 | to have a modern version of Java (>= JRE 1.6) to use it. One installed, this command may be used for more information: 21 | 22 | ``` 23 | antlr4ts 24 | ``` 25 | 26 | For general See general information about ANTLR see http://www.antlr.org -------------------------------------------------------------------------------- /tool/antlr4ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require("antlr4ts-cli") 4 | -------------------------------------------------------------------------------- /tool/index.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | 6 | var child_process = require('child_process'); 7 | var path = require('path'); 8 | var process = require('process'); 9 | 10 | var cmd = 'java'; 11 | var value = ['-jar', path.join(__dirname, 'target/antlr4-typescript-4.9.0-SNAPSHOT-complete.jar')] 12 | .concat(process.argv.slice(2)); 13 | var opt = {stdio: "inherit"}; 14 | 15 | var child = child_process.spawn(cmd, value, opt); 16 | 17 | // child.stderr.on('data', function (data) { 18 | // console.error(''+data); 19 | // }); 20 | 21 | // child.stdout.on('data', function (data) { 22 | // console.log(''+data); 23 | // }); 24 | 25 | child.on('close', function (code) { 26 | process.exitCode = code; // Sets expected exit code without forcing exit prior to buffers flushing. 27 | code && console.log("child process exited with code ", code); 28 | }); 29 | -------------------------------------------------------------------------------- /tool/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "antlr4ts-cli", 3 | "version": "0.5.0-dev", 4 | "lockfileVersion": 1 5 | } 6 | -------------------------------------------------------------------------------- /tool/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "antlr4ts-cli", 3 | "version": "0.5.0-dev", 4 | "preferGlobal": true, 5 | "description": "ANTLR 4 command line tool for TypeScript", 6 | "files": [ 7 | "LICENSE", 8 | "target/antlr4-typescript-4.9.0-SNAPSHOT-complete.jar", 9 | "antlr4ts", 10 | "index.js" 11 | ], 12 | "bin": { 13 | "antlr4ts": "./antlr4ts" 14 | }, 15 | "scripts": { 16 | "prepare": "mvn verify" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "git+https://github.com/tunnelvisionlabs/antlr4ts.git" 21 | }, 22 | "keywords": [ 23 | "ANTLR4", 24 | "typescript", 25 | "tool" 26 | ], 27 | "author": "Terence Parr, Sam Harwell, and Burt Harris", 28 | "license": "BSD-3-Clause", 29 | "bugs": { 30 | "url": "https://github.com/tunnelvisionlabs/antlr4ts/issues" 31 | }, 32 | "homepage": "https://github.com/tunnelvisionlabs/antlr4ts/tool#readme" 33 | } 34 | -------------------------------------------------------------------------------- /tool/src/org/antlr/v4/TypeScriptTool.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | package org.antlr.v4; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.io.Writer; 10 | import java.util.HashMap; 11 | import org.antlr.v4.tool.ErrorType; 12 | import org.antlr.v4.tool.Grammar; 13 | 14 | /** 15 | * 16 | * @author Sam Harwell 17 | */ 18 | public class TypeScriptTool extends Tool { 19 | private boolean verbose = false; 20 | 21 | static { 22 | Grammar.parserOptions.add("baseImportPath"); 23 | Grammar.lexerOptions.add("baseImportPath"); 24 | } 25 | 26 | public TypeScriptTool() { 27 | this(null); 28 | } 29 | 30 | public TypeScriptTool(String[] args) { 31 | super(args); 32 | if (grammarEncoding == null) { 33 | grammarEncoding = "UTF-8"; 34 | } 35 | 36 | if (grammarOptions == null) { 37 | grammarOptions = new HashMap(); 38 | } 39 | 40 | grammarOptions.put("language", "TypeScript"); 41 | } 42 | 43 | public static void main(String[] args) { 44 | TypeScriptTool antlr = new TypeScriptTool(args); 45 | antlr.verbose = true; 46 | if (args.length == 0) { 47 | antlr.help(); 48 | antlr.exit(0); 49 | } 50 | 51 | try { 52 | antlr.processGrammarsOnCommandLine(); 53 | } finally { 54 | if (antlr.log) { 55 | try { 56 | String logname = antlr.logMgr.save(); 57 | System.out.println("wrote " + logname); 58 | } 59 | catch (IOException ioe) { 60 | antlr.errMgr.toolError(ErrorType.INTERNAL_ERROR, ioe); 61 | } 62 | } 63 | } 64 | 65 | if (antlr.return_dont_exit) { 66 | return; 67 | } 68 | 69 | if (antlr.errMgr.getNumErrors() > 0) { 70 | antlr.exit(1); 71 | } 72 | 73 | antlr.exit(0); 74 | } 75 | 76 | @Override 77 | public Writer getOutputFileWriter(Grammar g, String fileName) throws IOException { 78 | if (outputDirectory != null) { 79 | // output directory is a function of where the grammar file lives 80 | // for subdir/T.g4, you get subdir here. Well, depends on -o etc... 81 | File outputDir = getOutputDirectory(g.fileName); 82 | File outputFile = new File(outputDir, fileName); 83 | if (this.verbose) { 84 | System.out.format("Generating file '%s' for grammar '%s'%n", outputFile.getAbsolutePath(), g.fileName); 85 | } 86 | } 87 | 88 | return super.getOutputFileWriter(g, fileName); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /tool/test/org/antlr/v4/test/runtime/typescript/ErrorQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The ANTLR Project. All rights reserved. 3 | * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. 4 | */ 5 | package org.antlr.v4.test.runtime.typescript; 6 | 7 | import org.antlr.v4.Tool; 8 | import org.antlr.v4.runtime.misc.Utils; 9 | import org.antlr.v4.tool.ANTLRMessage; 10 | import org.antlr.v4.tool.ANTLRToolListener; 11 | import org.antlr.v4.tool.ToolMessage; 12 | import org.stringtemplate.v4.ST; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | public class ErrorQueue implements ANTLRToolListener { 18 | public final Tool tool; 19 | public final List infos = new ArrayList(); 20 | public final List errors = new ArrayList(); 21 | public final List warnings = new ArrayList(); 22 | public final List all = new ArrayList(); 23 | 24 | public ErrorQueue() { 25 | this(null); 26 | } 27 | 28 | public ErrorQueue(Tool tool) { 29 | this.tool = tool; 30 | } 31 | 32 | @Override 33 | public void info(String msg) { 34 | infos.add(msg); 35 | } 36 | 37 | @Override 38 | public void error(ANTLRMessage msg) { 39 | errors.add(msg); 40 | all.add(msg); 41 | } 42 | 43 | @Override 44 | public void warning(ANTLRMessage msg) { 45 | warnings.add(msg); 46 | all.add(msg); 47 | } 48 | 49 | public void error(ToolMessage msg) { 50 | errors.add(msg); 51 | all.add(msg); 52 | } 53 | 54 | public int size() { 55 | return all.size() + infos.size(); 56 | } 57 | 58 | @Override 59 | public String toString() { 60 | return toString(false); 61 | } 62 | 63 | public String toString(boolean rendered) { 64 | if (!rendered) { 65 | return Utils.join(all.iterator(), "\n"); 66 | } 67 | 68 | if (tool == null) { 69 | throw new IllegalStateException(String.format("No %s instance is available.", Tool.class.getName())); 70 | } 71 | 72 | StringBuilder buf = new StringBuilder(); 73 | for (ANTLRMessage m : all) { 74 | ST st = tool.errMgr.getMessageTemplate(m); 75 | buf.append(st.render()); 76 | buf.append("\n"); 77 | } 78 | 79 | return buf.toString(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /tool/test/org/antlr/v4/test/runtime/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "antlr4ts-test", 3 | "version": "0.0.0", 4 | "description": "Unit test project for the ANTLR 4 TypeScript target", 5 | "main": "index.js", 6 | "private": true, 7 | "scripts": { 8 | "prepublish": "tsc", 9 | "test": "tsc" 10 | }, 11 | "devDependencies": { 12 | "@types/node": "^6.0.41", 13 | "source-map-support": "^0.4.3", 14 | "typescript": "^2.0.3" 15 | }, 16 | "dependencies": { 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tool/test/org/antlr/v4/test/runtime/typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "module": "commonjs", 5 | "target": "es2015", 6 | "lib": [ 7 | "es6" 8 | ], 9 | "noImplicitAny": true, 10 | "strictNullChecks": true, 11 | "experimentalDecorators": true, 12 | "declaration": false, 13 | "preserveConstEnums": true, 14 | "typeRoots": [ 15 | "./node_modules/@types" 16 | ], 17 | "types": [ 18 | "node" 19 | ] 20 | }, 21 | "include": [ 22 | "./*.ts" 23 | ], 24 | "exclude": [ 25 | "node_modules" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /tool/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "target", 4 | "sourceMap": true, 5 | "module": "commonjs", 6 | "target": "es2015", 7 | "lib": [ 8 | "es6" 9 | ], 10 | "noImplicitAny": true, 11 | "strictNullChecks": true, 12 | "experimentalDecorators": true, 13 | "declaration": true, 14 | "preserveConstEnums": true, 15 | "typeRoots": [ 16 | "./node_modules/@types" 17 | ], 18 | "types": [ 19 | "node", 20 | "mocha" 21 | ] 22 | }, 23 | "exclude": [ 24 | "node_modules", 25 | "target" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "target", 4 | "sourceMap": true, 5 | "inlineSources": true, 6 | "module": "commonjs", 7 | "target": "es2015", 8 | "lib": [ 9 | "es6" 10 | ], 11 | "noImplicitAny": true, 12 | "strict": true, 13 | "experimentalDecorators": true, 14 | "declaration": true, 15 | "preserveConstEnums": true, 16 | "typeRoots": [ 17 | "./node_modules/@types" 18 | ], 19 | "types": [ 20 | "node", 21 | "mocha" 22 | ] 23 | }, 24 | "exclude": [ 25 | "node_modules", 26 | "target", 27 | "tool", 28 | "test/runtime" 29 | ] 30 | } 31 | --------------------------------------------------------------------------------