├── .gitignore ├── .travis.yml ├── Readme.MD ├── antlr-kotlin-examples-js ├── .gitignore ├── antlr4 │ ├── BufferedTokenStream.js │ ├── CharStreams.js │ ├── CommonTokenFactory.js │ ├── CommonTokenStream.js │ ├── FileStream.js │ ├── InputStream.js │ ├── IntervalSet.js │ ├── LL1Analyzer.js │ ├── Lexer.js │ ├── Parser.js │ ├── ParserRuleContext.js │ ├── PredictionContext.js │ ├── README.md │ ├── Recognizer.js │ ├── RuleContext.js │ ├── Token.js │ ├── Utils.js │ ├── atn │ │ ├── ATN.js │ │ ├── ATNConfig.js │ │ ├── ATNConfigSet.js │ │ ├── ATNDeserializationOptions.js │ │ ├── ATNDeserializer.js │ │ ├── ATNSimulator.js │ │ ├── ATNState.js │ │ ├── ATNType.js │ │ ├── LexerATNSimulator.js │ │ ├── LexerAction.js │ │ ├── LexerActionExecutor.js │ │ ├── ParserATNSimulator.js │ │ ├── PredictionMode.js │ │ ├── SemanticContext.js │ │ ├── Transition.js │ │ └── index.js │ ├── dfa │ │ ├── DFA.js │ │ ├── DFASerializer.js │ │ ├── DFAState.js │ │ └── index.js │ ├── error │ │ ├── DiagnosticErrorListener.js │ │ ├── ErrorListener.js │ │ ├── ErrorStrategy.js │ │ ├── Errors.js │ │ └── index.js │ ├── index.js │ ├── package.json │ ├── polyfills │ │ ├── codepointat.js │ │ └── fromcodepoint.js │ └── tree │ │ ├── Tree.js │ │ ├── Trees.js │ │ └── index.js ├── build.gradle ├── index.html ├── lib │ └── require.js └── src │ ├── main │ ├── antlr │ │ ├── MiniCalcLexer.g4 │ │ └── MiniCalcParser.g4 │ └── kotlin │ │ └── UsingLexer.kt │ └── test │ └── kotlin │ ├── MiniCalcLexerTest.kt │ ├── MiniCalcParserTest.kt │ └── MiscStringTest.kt ├── antlr-kotlin-examples-jvm ├── .gitignore ├── build.gradle └── src │ ├── main │ ├── antlr │ │ ├── MiniCalcLexer.g4 │ │ └── MiniCalcParser.g4 │ ├── java │ │ ├── MiniCalcLexer.interp │ │ └── MiniCalcLexer.tokens │ └── kotlin │ │ ├── UsingLexer.kt │ │ └── UsingParser.kt │ └── test │ └── kotlin │ ├── MiniCalcLexerTest.kt │ ├── MiniCalcParserTest.kt │ └── MiscStringTest.kt ├── antlr-kotlin-gradle-plugin ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── gradleplugin │ │ ├── AntlrKotlinPlugin.java │ │ ├── AntlrKotlinTask.java │ │ ├── AntlrSourceVirtualDirectory.java │ │ ├── internal │ │ ├── AntlrExecuter.java │ │ ├── AntlrResult.java │ │ ├── AntlrSourceGenerationException.java │ │ ├── AntlrSourceVirtualDirectoryImpl.java │ │ ├── AntlrSpec.java │ │ ├── AntlrSpecFactory.java │ │ ├── AntlrWorker.java │ │ └── AntlrWorkerManager.java │ │ └── package-info.java │ └── resources │ └── META-INF │ └── gradle-plugins │ └── com.strumenta.antlrkotlin.properties ├── antlr-kotlin-runtime-common ├── build.gradle └── src │ ├── main │ └── kotlin │ │ ├── com │ │ └── strumenta │ │ │ └── kotlinmultiplatform │ │ │ └── Misc.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ ├── ANTLRErrorListener.kt │ │ ├── ANTLRErrorStrategy.kt │ │ ├── ANTLRFileStream.kt │ │ ├── ANTLRInputStream.kt │ │ ├── BailErrorStrategy.kt │ │ ├── BaseErrorListener.kt │ │ ├── BufferedTokenStream.kt │ │ ├── CharStream.kt │ │ ├── CommonToken.kt │ │ ├── CommonTokenFactory.kt │ │ ├── CommonTokenStream.kt │ │ ├── ConsoleErrorListener.kt │ │ ├── DefaultErrorStrategy.kt │ │ ├── DiagnosticErrorListener.kt │ │ ├── FailedPredicateException.kt │ │ ├── InputMismatchException.kt │ │ ├── IntStream.kt │ │ ├── InterpreterRuleContext.kt │ │ ├── Lexer.kt │ │ ├── LexerInterpreter.kt │ │ ├── LexerNoViableAltException.kt │ │ ├── ListTokenSource.kt │ │ ├── NoViableAltException.kt │ │ ├── Parser.kt │ │ ├── ParserInterpreter.kt │ │ ├── ParserRuleContext.kt │ │ ├── ProxyErrorListener.kt │ │ ├── RecognitionException.kt │ │ ├── Recognizer.kt │ │ ├── RuleContext.kt │ │ ├── RuleContextWithAltNum.kt │ │ ├── RuntimeMetaData.kt │ │ ├── Token.kt │ │ ├── TokenFactory.kt │ │ ├── TokenSource.kt │ │ ├── TokenStream.kt │ │ ├── TokenStreamRewriter.kt │ │ ├── UnbufferedCharStream.kt │ │ ├── UnbufferedTokenStream.kt │ │ ├── Vocabulary.kt │ │ ├── VocabularyImpl.kt │ │ ├── WritableToken.kt │ │ ├── ast │ │ ├── Node.kt │ │ └── position.kt │ │ ├── atn │ │ ├── ATN.kt │ │ ├── ATNConfig.kt │ │ ├── ATNConfigSet.kt │ │ ├── ATNDeserializationOptions.kt │ │ ├── ATNDeserializer.kt │ │ ├── ATNSerializer.kt │ │ ├── ATNSimulator.kt │ │ ├── ATNState.kt │ │ ├── ATNType.kt │ │ ├── AbstractPredicateTransition.kt │ │ ├── ActionTransition.kt │ │ ├── AmbiguityInfo.kt │ │ ├── ArrayPredictionContext.kt │ │ ├── AtomTransition.kt │ │ ├── BasicBlockStartState.kt │ │ ├── BasicState.kt │ │ ├── BlockEndState.kt │ │ ├── BlockStartState.kt │ │ ├── CodePointTransitions.kt │ │ ├── ContextSensitivityInfo.kt │ │ ├── DecisionEventInfo.kt │ │ ├── DecisionInfo.kt │ │ ├── DecisionState.kt │ │ ├── EmptyPredictionContext.kt │ │ ├── EpsilonTransition.kt │ │ ├── ErrorInfo.kt │ │ ├── LL1Analyzer.kt │ │ ├── LexerATNConfig.kt │ │ ├── LexerATNSimulator.kt │ │ ├── LexerAction.kt │ │ ├── LexerActionExecutor.kt │ │ ├── LexerActionType.kt │ │ ├── LexerChannelAction.kt │ │ ├── LexerCustomAction.kt │ │ ├── LexerIndexedCustomAction.kt │ │ ├── LexerModeAction.kt │ │ ├── LexerMoreAction.kt │ │ ├── LexerPopModeAction.kt │ │ ├── LexerPushModeAction.kt │ │ ├── LexerSkipAction.kt │ │ ├── LexerTypeAction.kt │ │ ├── LookaheadEventInfo.kt │ │ ├── LoopEndState.kt │ │ ├── NotSetTransition.kt │ │ ├── OrderedATNConfigSet.kt │ │ ├── ParseInfo.kt │ │ ├── ParserATNSimulator.kt │ │ ├── PlusBlockStartState.kt │ │ ├── PlusLoopbackState.kt │ │ ├── PrecedencePredicateTransition.kt │ │ ├── PredicateEvalInfo.kt │ │ ├── PredicateTransition.kt │ │ ├── PredictionContext.kt │ │ ├── PredictionContextCache.kt │ │ ├── PredictionMode.kt │ │ ├── ProfilingATNSimulator.kt │ │ ├── RangeTransition.kt │ │ ├── RuleStartState.kt │ │ ├── RuleStopState.kt │ │ ├── RuleTransition.kt │ │ ├── SemanticContext.kt │ │ ├── SetTransition.kt │ │ ├── SingletonPredictionContext.kt │ │ ├── StarBlockStartState.kt │ │ ├── StarLoopEntryState.kt │ │ ├── StarLoopbackState.kt │ │ ├── TokensStartState.kt │ │ ├── Transition.kt │ │ └── WildcardTransition.kt │ │ ├── dfa │ │ ├── DFA.kt │ │ ├── DFASerializer.kt │ │ ├── DFAState.kt │ │ └── LexerDFASerializer.kt │ │ ├── misc │ │ ├── AbstractEqualityComparator.kt │ │ ├── Array2DHashSet.kt │ │ ├── DoubleKeyMap.kt │ │ ├── EqualityComparator.kt │ │ ├── FlexibleHashMap.kt │ │ ├── IntSet.kt │ │ ├── IntegerList.kt │ │ ├── IntegerStack.kt │ │ ├── InterpreterDataReader.kt │ │ ├── Interval.kt │ │ ├── IntervalSet.kt │ │ ├── LogManager.kt │ │ ├── MultiMap.kt │ │ ├── MurmurHash.kt │ │ ├── NotNull.kt │ │ ├── ObjectEqualityComparator.kt │ │ ├── OrderedHashSet.kt │ │ ├── Pair.kt │ │ ├── ParseCancellationException.kt │ │ ├── Predicate.kt │ │ ├── Triple.kt │ │ └── Utils.kt │ │ └── tree │ │ ├── AbstractParseTreeVisitor.kt │ │ ├── ErrorNode.kt │ │ ├── ErrorNodeImpl.kt │ │ ├── IterativeParseTreeWalker.kt │ │ ├── ParseTree.kt │ │ ├── ParseTreeListener.kt │ │ ├── ParseTreeProperty.kt │ │ ├── ParseTreeVisitor.kt │ │ ├── ParseTreeWalker.kt │ │ ├── RuleNode.kt │ │ ├── SyntaxTree.kt │ │ ├── TerminalNode.kt │ │ ├── TerminalNodeImpl.kt │ │ ├── Tree.kt │ │ ├── Trees.kt │ │ ├── pattern │ │ ├── Chunk.kt │ │ ├── ParseTreeMatch.kt │ │ ├── ParseTreePattern.kt │ │ ├── ParseTreePatternMatcher.kt │ │ ├── RuleTagToken.kt │ │ ├── TagChunk.kt │ │ ├── TextChunk.kt │ │ └── TokenTagToken.kt │ │ └── xpath │ │ ├── XPath.kt │ │ ├── XPathElement.kt │ │ ├── XPathLexer.kt │ │ ├── XPathLexerErrorListener.kt │ │ ├── XPathRuleAnywhereElement.kt │ │ ├── XPathRuleElement.kt │ │ ├── XPathTokenAnywhereElement.kt │ │ ├── XPathTokenElement.kt │ │ ├── XPathWildcardAnywhereElement.kt │ │ └── XPathWildcardElement.kt │ └── test │ └── kotlin │ ├── BaseTest.kt │ ├── LocalListener.kt │ ├── MiniCalcLexerTest.kt │ ├── MiniCalcParserTest.kt │ ├── StringTest.kt │ ├── com │ └── strumenta │ │ └── minicalc │ │ ├── MiniCalcLexer.kt │ │ ├── MiniCalcParser.kt │ │ ├── MiniCalcParserBaseListener.kt │ │ └── MiniCalcParserListener.kt │ └── org │ └── antlr │ └── v4 │ └── kotlinruntime │ └── misc │ └── IntegerListTest.kt ├── antlr-kotlin-runtime-js ├── .gitignore ├── build.gradle └── src │ └── main │ └── kotlin │ └── com │ └── strumenta │ └── kotlinmultiplatform │ ├── BitSet.kt │ ├── Collections.kt │ ├── IdentityHashMap.kt │ ├── Math.kt │ ├── NullPointerException.kt │ ├── RuntimeException.kt │ ├── UUID.kt │ ├── WeakHashMap.kt │ ├── arrays.kt │ ├── chars.kt │ ├── logging.kt │ └── type.kt ├── antlr-kotlin-runtime-jvm ├── build.gradle └── src │ └── main │ └── kotlin │ ├── com │ └── strumenta │ │ └── kotlinmultiplatform │ │ ├── BitSet.kt │ │ ├── Collections.kt │ │ ├── IdentityHashMap.kt │ │ ├── Math.kt │ │ ├── NullPointerException.kt │ │ ├── RuntimeException.kt │ │ ├── UUID.kt │ │ ├── WeakHashMap.kt │ │ ├── arrays.kt │ │ ├── chars.kt │ │ ├── logging.kt │ │ └── type.kt │ └── org │ └── antlr │ └── v4 │ └── kotlinruntime │ ├── CharStreams.kt │ ├── CodePointBuffer.kt │ └── CodePointCharStream.kt ├── antlr-kotlin-target ├── build.gradle └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── antlr │ │ │ └── v4 │ │ │ └── codegen │ │ │ └── target │ │ │ └── KotlinTarget.java │ └── resources │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── tool │ │ └── templates │ │ └── codegen │ │ └── Kotlin │ │ └── Kotlin.stg │ └── test │ ├── kotlin │ └── Example.kt │ └── resources │ ├── MiniCalcLexer.g4 │ ├── MiniCalcLexer.interp │ ├── MiniCalcLexer.java │ ├── MiniCalcLexer.kt │ ├── MiniCalcLexer.tokens │ ├── MiniCalcParser.g4 │ ├── MiniCalcParser.interp │ ├── MiniCalcParser.java │ ├── MiniCalcParser.kt │ ├── MiniCalcParser.tokens │ ├── MiniCalcParserBaseListener.java │ ├── MiniCalcParserBaseListener.kt │ ├── MiniCalcParserListener.java │ └── MiniCalcParserListener.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build 3 | **/*.iml 4 | **/*.ipr 5 | **/*.iws 6 | .idea 7 | out 8 | **/.DS_Store 9 | .java-version 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | install: true 5 | script: 6 | - ./gradlew :antlr-kotlin-runtime-jvm:test 7 | - ./gradlew :antlr-kotlin-runtime-js:test 8 | - ./gradlew :antlr-kotlin-runtime-common:install 9 | - ./gradlew :antlr-kotlin-runtime-jvm:install 10 | - ./gradlew :antlr-kotlin-runtime-js:install 11 | - ./gradlew :antlr-kotlin-target:install 12 | - ./gradlew :antlr-kotlin-gradle-plugin:install 13 | - cd antlr-kotlin-examples-jvm && ../gradlew check && cd .. 14 | # - cd antlr-kotlin-examples-js && ../gradlew check && cd .. 15 | 16 | -------------------------------------------------------------------------------- /Readme.MD: -------------------------------------------------------------------------------- 1 | **The project moved here: [Strumenta/antlr-kotlin](https://github.com/Strumenta/antlr-kotlin/)** 2 | 3 | # ANTLR Kotlin 4 | 5 | The Kotlin target for ANTLR. 6 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | js 3 | generated-src 4 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/CharStreams.js: -------------------------------------------------------------------------------- 1 | // 2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | // 7 | 8 | var InputStream = require('./InputStream').InputStream; 9 | 10 | var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined'; 11 | var fs = isNodeJs ? require("fs") : null; 12 | 13 | // Utility functions to create InputStreams from various sources. 14 | // 15 | // All returned InputStreams support the full range of Unicode 16 | // up to U+10FFFF (the default behavior of InputStream only supports 17 | // code points up to U+FFFF). 18 | var CharStreams = { 19 | // Creates an InputStream from a string. 20 | fromString: function(str) { 21 | return new InputStream(str, true); 22 | }, 23 | 24 | // Asynchronously creates an InputStream from a blob given the 25 | // encoding of the bytes in that blob (defaults to 'utf8' if 26 | // encoding is null). 27 | // 28 | // Invokes onLoad(result) on success, onError(error) on 29 | // failure. 30 | fromBlob: function(blob, encoding, onLoad, onError) { 31 | var reader = FileReader(); 32 | reader.onload = function(e) { 33 | var is = new InputStream(e.target.result, true); 34 | onLoad(is); 35 | }; 36 | reader.onerror = onError; 37 | reader.readAsText(blob, encoding); 38 | }, 39 | 40 | // Creates an InputStream from a Buffer given the 41 | // encoding of the bytes in that buffer (defaults to 'utf8' if 42 | // encoding is null). 43 | fromBuffer: function(buffer, encoding) { 44 | return new InputStream(buffer.toString(encoding), true); 45 | }, 46 | 47 | // Asynchronously creates an InputStream from a file on disk given 48 | // the encoding of the bytes in that file (defaults to 'utf8' if 49 | // encoding is null). 50 | // 51 | // Invokes callback(error, result) on completion. 52 | fromPath: function(path, encoding, callback) { 53 | fs.readFile(path, encoding, function(err, data) { 54 | var is = null; 55 | if (data !== null) { 56 | is = new InputStream(data, true); 57 | } 58 | callback(err, is); 59 | }); 60 | }, 61 | 62 | // Synchronously creates an InputStream given a path to a file 63 | // on disk and the encoding of the bytes in that file (defaults to 64 | // 'utf8' if encoding is null). 65 | fromPathSync: function(path, encoding) { 66 | var data = fs.readFileSync(path, encoding); 67 | return new InputStream(data, true); 68 | } 69 | }; 70 | 71 | exports.CharStreams = CharStreams; 72 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/CommonTokenFactory.js: -------------------------------------------------------------------------------- 1 | // 2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | // 7 | 8 | // 9 | // This default implementation of {@link TokenFactory} creates 10 | // {@link CommonToken} objects. 11 | // 12 | 13 | var CommonToken = require('./Token').CommonToken; 14 | 15 | function TokenFactory() { 16 | return this; 17 | } 18 | 19 | function CommonTokenFactory(copyText) { 20 | TokenFactory.call(this); 21 | // Indicates whether {@link CommonToken//setText} should be called after 22 | // constructing tokens to explicitly set the text. This is useful for cases 23 | // where the input stream might not be able to provide arbitrary substrings 24 | // of text from the input after the lexer creates a token (e.g. the 25 | // implementation of {@link CharStream//getText} in 26 | // {@link UnbufferedCharStream} throws an 27 | // {@link UnsupportedOperationException}). Explicitly setting the token text 28 | // allows {@link Token//getText} to be called at any time regardless of the 29 | // input stream implementation. 30 | // 31 | //

32 | // The default value is {@code false} to avoid the performance and memory 33 | // overhead of copying text for every token unless explicitly requested.

34 | // 35 | this.copyText = copyText===undefined ? false : copyText; 36 | return this; 37 | } 38 | 39 | CommonTokenFactory.prototype = Object.create(TokenFactory.prototype); 40 | CommonTokenFactory.prototype.constructor = CommonTokenFactory; 41 | 42 | // 43 | // The default {@link CommonTokenFactory} instance. 44 | // 45 | //

46 | // This token factory does not explicitly copy token text when constructing 47 | // tokens.

48 | // 49 | CommonTokenFactory.DEFAULT = new CommonTokenFactory(); 50 | 51 | CommonTokenFactory.prototype.create = function(source, type, text, channel, start, stop, line, column) { 52 | var t = new CommonToken(source, type, channel, start, stop); 53 | t.line = line; 54 | t.column = column; 55 | if (text !==null) { 56 | t.text = text; 57 | } else if (this.copyText && source[1] !==null) { 58 | t.text = source[1].getText(start,stop); 59 | } 60 | return t; 61 | }; 62 | 63 | CommonTokenFactory.prototype.createThin = function(type, text) { 64 | var t = new CommonToken(null, type); 65 | t.text = text; 66 | return t; 67 | }; 68 | 69 | exports.CommonTokenFactory = CommonTokenFactory; 70 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/FileStream.js: -------------------------------------------------------------------------------- 1 | // 2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | // 7 | 8 | // 9 | // This is an InputStream that is loaded from a file all at once 10 | // when you construct the object. 11 | // 12 | var InputStream = require('./InputStream').InputStream; 13 | var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined'; 14 | var fs = isNodeJs ? require("fs") : null; 15 | 16 | function FileStream(fileName, decodeToUnicodeCodePoints) { 17 | var data = fs.readFileSync(fileName, "utf8"); 18 | InputStream.call(this, data, decodeToUnicodeCodePoints); 19 | this.fileName = fileName; 20 | return this; 21 | } 22 | 23 | FileStream.prototype = Object.create(InputStream.prototype); 24 | FileStream.prototype.constructor = FileStream; 25 | 26 | exports.FileStream = FileStream; 27 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/README.md: -------------------------------------------------------------------------------- 1 | # JavaScript target for ANTLR 4 2 | 3 | JavaScript runtime libraries for ANTLR 4 4 | 5 | This runtime is available through npm. The package name is 'antlr4'. 6 | 7 | This runtime has been tested in Node.js, Safari, Firefox, Chrome and IE. 8 | 9 | See www.antlr.org for more information on ANTLR 10 | 11 | See https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md for more information on using ANTLR in JavaScript 12 | 13 | 14 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/atn/ATNDeserializationOptions.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | 6 | function ATNDeserializationOptions(copyFrom) { 7 | if(copyFrom===undefined) { 8 | copyFrom = null; 9 | } 10 | this.readOnly = false; 11 | this.verifyATN = copyFrom===null ? true : copyFrom.verifyATN; 12 | this.generateRuleBypassTransitions = copyFrom===null ? false : copyFrom.generateRuleBypassTransitions; 13 | 14 | return this; 15 | } 16 | 17 | ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions(); 18 | ATNDeserializationOptions.defaultOptions.readOnly = true; 19 | 20 | // def __setattr__(self, key, value): 21 | // if key!="readOnly" and self.readOnly: 22 | // raise Exception("The object is read only.") 23 | // super(type(self), self).__setattr__(key,value) 24 | 25 | exports.ATNDeserializationOptions = ATNDeserializationOptions; 26 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/atn/ATNSimulator.js: -------------------------------------------------------------------------------- 1 | // 2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | /// 7 | 8 | var DFAState = require('./../dfa/DFAState').DFAState; 9 | var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet; 10 | var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext; 11 | 12 | function ATNSimulator(atn, sharedContextCache) { 13 | 14 | // The context cache maps all PredictionContext objects that are == 15 | // to a single cached copy. This cache is shared across all contexts 16 | // in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet 17 | // to use only cached nodes/graphs in addDFAState(). We don't want to 18 | // fill this during closure() since there are lots of contexts that 19 | // pop up but are not used ever again. It also greatly slows down closure(). 20 | // 21 | //

This cache makes a huge difference in memory and a little bit in speed. 22 | // For the Java grammar on java.*, it dropped the memory requirements 23 | // at the end from 25M to 16M. We don't store any of the full context 24 | // graphs in the DFA because they are limited to local context only, 25 | // but apparently there's a lot of repetition there as well. We optimize 26 | // the config contexts before storing the config set in the DFA states 27 | // by literally rebuilding them with cached subgraphs only.

28 | // 29 | //

I tried a cache for use during closure operations, that was 30 | // whacked after each adaptivePredict(). It cost a little bit 31 | // more time I think and doesn't save on the overall footprint 32 | // so it's not worth the complexity.

33 | /// 34 | this.atn = atn; 35 | this.sharedContextCache = sharedContextCache; 36 | return this; 37 | } 38 | 39 | // Must distinguish between missing edge and edge we know leads nowhere/// 40 | ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet()); 41 | 42 | 43 | ATNSimulator.prototype.getCachedContext = function(context) { 44 | if (this.sharedContextCache ===null) { 45 | return context; 46 | } 47 | var visited = {}; 48 | return getCachedPredictionContext(context, this.sharedContextCache, visited); 49 | }; 50 | 51 | exports.ATNSimulator = ATNSimulator; 52 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/atn/ATNType.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | /// 6 | 7 | // Represents the type of recognizer an ATN applies to. 8 | 9 | function ATNType() { 10 | 11 | } 12 | 13 | ATNType.LEXER = 0; 14 | ATNType.PARSER = 1; 15 | 16 | exports.ATNType = ATNType; 17 | 18 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/atn/index.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | 6 | exports.ATN = require('./ATN').ATN; 7 | exports.ATNDeserializer = require('./ATNDeserializer').ATNDeserializer; 8 | exports.LexerATNSimulator = require('./LexerATNSimulator').LexerATNSimulator; 9 | exports.ParserATNSimulator = require('./ParserATNSimulator').ParserATNSimulator; 10 | exports.PredictionMode = require('./PredictionMode').PredictionMode; 11 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/dfa/index.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | 6 | exports.DFA = require('./DFA').DFA; 7 | exports.DFASerializer = require('./DFASerializer').DFASerializer; 8 | exports.LexerDFASerializer = require('./DFASerializer').LexerDFASerializer; 9 | exports.PredPrediction = require('./DFAState').PredPrediction; 10 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/error/index.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | 6 | exports.RecognitionException = require('./Errors').RecognitionException; 7 | exports.NoViableAltException = require('./Errors').NoViableAltException; 8 | exports.LexerNoViableAltException = require('./Errors').LexerNoViableAltException; 9 | exports.InputMismatchException = require('./Errors').InputMismatchException; 10 | exports.FailedPredicateException = require('./Errors').FailedPredicateException; 11 | exports.DiagnosticErrorListener = require('./DiagnosticErrorListener').DiagnosticErrorListener; 12 | exports.BailErrorStrategy = require('./ErrorStrategy').BailErrorStrategy; 13 | exports.ErrorListener = require('./ErrorListener').ErrorListener; 14 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/index.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | exports.atn = require('./atn/index'); 6 | exports.codepointat = require('./polyfills/codepointat'); 7 | exports.dfa = require('./dfa/index'); 8 | exports.fromcodepoint = require('./polyfills/fromcodepoint'); 9 | exports.tree = require('./tree/index'); 10 | exports.error = require('./error/index'); 11 | exports.Token = require('./Token').Token; 12 | exports.CharStreams = require('./CharStreams').CharStreams; 13 | exports.CommonToken = require('./Token').CommonToken; 14 | exports.InputStream = require('./InputStream').InputStream; 15 | exports.FileStream = require('./FileStream').FileStream; 16 | exports.CommonTokenStream = require('./CommonTokenStream').CommonTokenStream; 17 | exports.Lexer = require('./Lexer').Lexer; 18 | exports.Parser = require('./Parser').Parser; 19 | var pc = require('./PredictionContext'); 20 | exports.PredictionContextCache = pc.PredictionContextCache; 21 | exports.ParserRuleContext = require('./ParserRuleContext').ParserRuleContext; 22 | exports.Interval = require('./IntervalSet').Interval; 23 | exports.Utils = require('./Utils'); 24 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "antlr4", 3 | "version": "4.7.1", 4 | "description": "JavaScript runtime for ANTLR4", 5 | "main": "src/antlr4/index.js", 6 | "repository": "antlr/antlr4.git", 7 | "keywords": [ 8 | "lexer", 9 | "parser", 10 | "antlr", 11 | "antlr4", 12 | "grammar" 13 | ], 14 | "license": "BSD", 15 | "bugs": { 16 | "url": "https://github.com/antlr/antlr4/issues" 17 | }, 18 | "homepage": "https://github.com/antlr/antlr4" 19 | } 20 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/polyfills/codepointat.js: -------------------------------------------------------------------------------- 1 | /*! https://mths.be/codepointat v0.2.0 by @mathias */ 2 | if (!String.prototype.codePointAt) { 3 | (function() { 4 | 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` 5 | var defineProperty = (function() { 6 | // IE 8 only supports `Object.defineProperty` on DOM elements 7 | try { 8 | var object = {}; 9 | var $defineProperty = Object.defineProperty; 10 | var result = $defineProperty(object, object, object) && $defineProperty; 11 | } catch(error) {} 12 | return result; 13 | }()); 14 | var codePointAt = function(position) { 15 | if (this == null) { 16 | throw TypeError(); 17 | } 18 | var string = String(this); 19 | var size = string.length; 20 | // `ToInteger` 21 | var index = position ? Number(position) : 0; 22 | if (index != index) { // better `isNaN` 23 | index = 0; 24 | } 25 | // Account for out-of-bounds indices: 26 | if (index < 0 || index >= size) { 27 | return undefined; 28 | } 29 | // Get the first code unit 30 | var first = string.charCodeAt(index); 31 | var second; 32 | if ( // check if it’s the start of a surrogate pair 33 | first >= 0xD800 && first <= 0xDBFF && // high surrogate 34 | size > index + 1 // there is a next code unit 35 | ) { 36 | second = string.charCodeAt(index + 1); 37 | if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate 38 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae 39 | return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; 40 | } 41 | } 42 | return first; 43 | }; 44 | if (defineProperty) { 45 | defineProperty(String.prototype, 'codePointAt', { 46 | 'value': codePointAt, 47 | 'configurable': true, 48 | 'writable': true 49 | }); 50 | } else { 51 | String.prototype.codePointAt = codePointAt; 52 | } 53 | }()); 54 | } 55 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/polyfills/fromcodepoint.js: -------------------------------------------------------------------------------- 1 | /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */ 2 | if (!String.fromCodePoint) { 3 | (function() { 4 | var defineProperty = (function() { 5 | // IE 8 only supports `Object.defineProperty` on DOM elements 6 | try { 7 | var object = {}; 8 | var $defineProperty = Object.defineProperty; 9 | var result = $defineProperty(object, object, object) && $defineProperty; 10 | } catch(error) {} 11 | return result; 12 | }()); 13 | var stringFromCharCode = String.fromCharCode; 14 | var floor = Math.floor; 15 | var fromCodePoint = function(_) { 16 | var MAX_SIZE = 0x4000; 17 | var codeUnits = []; 18 | var highSurrogate; 19 | var lowSurrogate; 20 | var index = -1; 21 | var length = arguments.length; 22 | if (!length) { 23 | return ''; 24 | } 25 | var result = ''; 26 | while (++index < length) { 27 | var codePoint = Number(arguments[index]); 28 | if ( 29 | !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` 30 | codePoint < 0 || // not a valid Unicode code point 31 | codePoint > 0x10FFFF || // not a valid Unicode code point 32 | floor(codePoint) != codePoint // not an integer 33 | ) { 34 | throw RangeError('Invalid code point: ' + codePoint); 35 | } 36 | if (codePoint <= 0xFFFF) { // BMP code point 37 | codeUnits.push(codePoint); 38 | } else { // Astral code point; split in surrogate halves 39 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae 40 | codePoint -= 0x10000; 41 | highSurrogate = (codePoint >> 10) + 0xD800; 42 | lowSurrogate = (codePoint % 0x400) + 0xDC00; 43 | codeUnits.push(highSurrogate, lowSurrogate); 44 | } 45 | if (index + 1 == length || codeUnits.length > MAX_SIZE) { 46 | result += stringFromCharCode.apply(null, codeUnits); 47 | codeUnits.length = 0; 48 | } 49 | } 50 | return result; 51 | }; 52 | if (defineProperty) { 53 | defineProperty(String, 'fromCodePoint', { 54 | 'value': fromCodePoint, 55 | 'configurable': true, 56 | 'writable': true 57 | }); 58 | } else { 59 | String.fromCodePoint = fromCodePoint; 60 | } 61 | }()); 62 | } 63 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/antlr4/tree/index.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 2 | * Use of this file is governed by the BSD 3-clause license that 3 | * can be found in the LICENSE.txt file in the project root. 4 | */ 5 | 6 | var Tree = require('./Tree'); 7 | exports.Trees = require('./Trees').Trees; 8 | exports.RuleNode = Tree.RuleNode; 9 | exports.ParseTreeListener = Tree.ParseTreeListener; 10 | exports.ParseTreeVisitor = Tree.ParseTreeVisitor; 11 | exports.ParseTreeWalker = Tree.ParseTreeWalker; 12 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 7 |
8 | 9 |
10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/src/main/antlr/MiniCalcParser.g4: -------------------------------------------------------------------------------- 1 | parser grammar MiniCalcParser; 2 | 3 | options { tokenVocab=MiniCalcLexer; } 4 | 5 | miniCalcFile : lines=line+ ; 6 | 7 | line : statement (NEWLINE | EOF) ; 8 | 9 | statement : inputDeclaration # inputDeclarationStatement 10 | | varDeclaration # varDeclarationStatement 11 | | assignment # assignmentStatement 12 | | print # printStatement ; 13 | 14 | print : PRINT LPAREN expression RPAREN ; 15 | 16 | inputDeclaration : INPUT type name=ID ; 17 | 18 | varDeclaration : VAR assignment ; 19 | 20 | assignment : ID ASSIGN expression ; 21 | 22 | expression : left=expression operator=(DIVISION|ASTERISK) right=expression # binaryOperation 23 | | left=expression operator=(PLUS|MINUS) right=expression # binaryOperation 24 | | value=expression AS targetType=type # typeConversion 25 | | LPAREN expression RPAREN # parenExpression 26 | | ID # valueReference 27 | | MINUS expression # minusExpression 28 | | STRING_OPEN (parts+=stringLiteralContent)* STRING_CLOSE # stringLiteral 29 | | INTLIT # intLiteral 30 | | DECLIT # decimalLiteral ; 31 | 32 | stringLiteralContent : STRING_CONTENT # constantString 33 | | INTERPOLATION_OPEN expression INTERPOLATION_CLOSE # interpolatedValue ; 34 | 35 | type : INT # integer 36 | | DECIMAL # decimal 37 | | STRING # string ; 38 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/src/main/kotlin/UsingLexer.kt: -------------------------------------------------------------------------------- 1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream 2 | import org.antlr.v4.kotlinruntime.Token 3 | 4 | fun main(args: Array) { 5 | 6 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) { 7 | // throw RuntimeException("DIFFERENT LENGTHS") 8 | // } 9 | // for (i in 0..MiniCalcLexer.serializedATN.length) { 10 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) { 11 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}") 12 | // } 13 | // } 14 | 15 | val input = ANTLRInputStream("1 + 2") 16 | val lexer = MiniCalcLexer(input) 17 | var token : Token? = null 18 | do { 19 | token = lexer.nextToken() 20 | println("TOKEN $token") 21 | 22 | } while (token?.type != -1) 23 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/src/test/kotlin/MiniCalcLexerTest.kt: -------------------------------------------------------------------------------- 1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream 2 | import org.antlr.v4.kotlinruntime.atn.EmptyPredictionContext 3 | import org.antlr.v4.kotlinruntime.atn.PredictionContext 4 | import kotlin.test.* 5 | 6 | class TestingLexer { 7 | 8 | @Test fun firstTokenDebug1() { 9 | val input = ANTLRInputStream("1 + 2") 10 | val lexer = MiniCalcLexer(input) 11 | val interpreter = lexer.interpreter 12 | val result = interpreter!!.match(input, 0) 13 | assertEquals(11, result) 14 | } 15 | 16 | @Test fun checkMaxs() { 17 | assertEquals(2147483647, PredictionContext.EMPTY_RETURN_STATE) 18 | } 19 | 20 | @Test fun emptyPredictionContext() { 21 | assertEquals(true, EmptyPredictionContext().hasEmptyPath()) 22 | assertEquals(true, EmptyPredictionContext().isEmpty) 23 | } 24 | 25 | @Test fun firstTokenDebug2() { 26 | val input = ANTLRInputStream("1 + 2") 27 | val lexer = MiniCalcLexer(input) 28 | val interpreter = lexer.interpreter 29 | val decisionToDFA = interpreter!!.decisionToDFA 30 | val mode = 0 31 | val dfa = decisionToDFA[mode] 32 | assertEquals(true, dfa!!.s0 != null) 33 | assertEquals(0, dfa!!.s0!!.stateNumber) 34 | } 35 | 36 | @Test fun firstToken() { 37 | val input = ANTLRInputStream("1 + 2") 38 | val lexer = MiniCalcLexer(input) 39 | val token = lexer.nextToken() 40 | 41 | assertEquals("1", token.text) 42 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, token.type) 43 | } 44 | 45 | @Test fun simpleTokens() { 46 | val input = ANTLRInputStream("1 + 2") 47 | val lexer = MiniCalcLexer(input) 48 | val tokens = lexer.allTokens 49 | assertEquals(5, tokens.size) 50 | 51 | var i = 0 52 | assertEquals("1", tokens[i].text) 53 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type) 54 | 55 | i++ 56 | assertEquals(" ", tokens[i].text) 57 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type) 58 | 59 | i++ 60 | assertEquals("+", tokens[i].text) 61 | assertEquals(MiniCalcLexer.Tokens.PLUS.id, tokens[i].type) 62 | 63 | i++ 64 | assertEquals(" ", tokens[i].text) 65 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type) 66 | 67 | i++ 68 | assertEquals("2", tokens[i].text) 69 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type) 70 | } 71 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-js/src/test/kotlin/MiscStringTest.kt: -------------------------------------------------------------------------------- 1 | import com.strumenta.kotlinmultiplatform.toCharArray 2 | import kotlin.test.* 3 | 4 | fun assertArrayEquals(a: CharArray, b: CharArray) { 5 | assertEquals(a.size, b.size) 6 | for (i in 0..a.size) { 7 | assertEquals(a[i], b[i]) 8 | } 9 | } 10 | 11 | class MiscStringTest { 12 | 13 | @Test fun testToCharArrayEmpty() { 14 | assertArrayEquals(charArrayOf(), "".toCharArray()) 15 | } 16 | 17 | @Test fun testToCharArrayEmptyLength() { 18 | assertEquals(0, "".toCharArray().size) 19 | } 20 | 21 | @Test fun testToCharArrayEmptyEl0() { 22 | assertEquals('a', "abc def".toCharArray()[0]) 23 | } 24 | 25 | @Test fun testToCharArray() { 26 | assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray()) 27 | } 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/.gitignore: -------------------------------------------------------------------------------- 1 | generated-src 2 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlin_version = '1.2.60' 3 | ext.projectVersion = '0.0.2' 4 | ext.antlrKotlinVersion = projectVersion 5 | 6 | repositories { 7 | mavenCentral() 8 | mavenLocal() 9 | } 10 | dependencies { 11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 12 | classpath "com.strumenta.antlr-kotlin:antlr-kotlin-gradle-plugin:$projectVersion" 13 | } 14 | } 15 | 16 | apply plugin: 'kotlin' 17 | apply plugin: 'idea' 18 | apply plugin: 'com.strumenta.antlrkotlin' 19 | 20 | repositories { 21 | mavenCentral() 22 | mavenLocal() 23 | } 24 | 25 | dependencies { 26 | compile "com.strumenta.antlr-kotlin:antlr-kotlin-runtime-common:$projectVersion" 27 | compile "com.strumenta.antlr-kotlin:antlr-kotlin-runtime-jvm:$projectVersion" 28 | compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version" 29 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 30 | //testCompile 'junit:junit:4.12' 31 | } 32 | 33 | generateKotlinGrammarSource { 34 | version = projectVersion 35 | maxHeapSize = "64m" 36 | arguments += ['-package', 'me.tomassetti.minicalc'] 37 | outputDirectory = new File("generated-src/antlr/".toString()) 38 | } 39 | compileKotlin.dependsOn generateKotlinGrammarSource 40 | sourceSets { 41 | generated { 42 | kotlin.srcDir 'generated-src/antlr/' 43 | } 44 | } 45 | compileKotlin.source sourceSets.generated.kotlin, sourceSets.main.kotlin 46 | 47 | clean{ 48 | delete "generated-src" 49 | } 50 | 51 | idea { 52 | module { 53 | sourceDirs += file("generated-src/antlr/") 54 | } 55 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/main/antlr/MiniCalcParser.g4: -------------------------------------------------------------------------------- 1 | parser grammar MiniCalcParser; 2 | 3 | options { tokenVocab=MiniCalcLexer; } 4 | 5 | miniCalcFile : lines=line+ ; 6 | 7 | line : statement (NEWLINE | EOF) ; 8 | 9 | statement : inputDeclaration # inputDeclarationStatement 10 | | varDeclaration # varDeclarationStatement 11 | | assignment # assignmentStatement 12 | | print # printStatement ; 13 | 14 | print : PRINT LPAREN expression RPAREN ; 15 | 16 | inputDeclaration : INPUT type name=ID ; 17 | 18 | varDeclaration : VAR assignment ; 19 | 20 | assignment : ID ASSIGN expression ; 21 | 22 | expression : left=expression operator=(DIVISION|ASTERISK) right=expression # binaryOperation 23 | | left=expression operator=(PLUS|MINUS) right=expression # binaryOperation 24 | | value=expression AS targetType=type # typeConversion 25 | | LPAREN expression RPAREN # parenExpression 26 | | ID # valueReference 27 | | MINUS expression # minusExpression 28 | | STRING_OPEN (parts+=stringLiteralContent)* STRING_CLOSE # stringLiteral 29 | | INTLIT # intLiteral 30 | | DECLIT # decimalLiteral ; 31 | 32 | stringLiteralContent : STRING_CONTENT # constantString 33 | | INTERPOLATION_OPEN expression INTERPOLATION_CLOSE # interpolatedValue ; 34 | 35 | type : INT # integer 36 | | DECIMAL # decimal 37 | | STRING # string ; 38 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/main/java/MiniCalcLexer.tokens: -------------------------------------------------------------------------------- 1 | NEWLINE=1 2 | WS=2 3 | INPUT=3 4 | VAR=4 5 | PRINT=5 6 | AS=6 7 | INT=7 8 | DECIMAL=8 9 | STRING=9 10 | ID=10 11 | INTLIT=11 12 | DECLIT=12 13 | PLUS=13 14 | MINUS=14 15 | ASTERISK=15 16 | DIVISION=16 17 | ASSIGN=17 18 | LPAREN=18 19 | RPAREN=19 20 | STRING_OPEN=20 21 | UNMATCHED=21 22 | ESCAPE_STRING_DELIMITER=22 23 | ESCAPE_SLASH=23 24 | ESCAPE_NEWLINE=24 25 | ESCAPE_SHARP=25 26 | STRING_CLOSE=26 27 | INTERPOLATION_OPEN=27 28 | STRING_CONTENT=28 29 | INTERPOLATION_CLOSE=29 30 | 'input'=3 31 | 'var'=4 32 | 'print'=5 33 | '\\"'=22 34 | '\\\\'=23 35 | '\\n'=24 36 | '\\#'=25 37 | '#{'=27 38 | '}'=29 39 | -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/main/kotlin/UsingLexer.kt: -------------------------------------------------------------------------------- 1 | 2 | import org.antlr.v4.kotlinruntime.ANTLRInputStream 3 | import org.antlr.v4.kotlinruntime.CharStream 4 | import org.antlr.v4.kotlinruntime.Token 5 | import java.lang.RuntimeException 6 | import me.tomassetti.minicalc.MiniCalcLexer 7 | 8 | fun main(args: Array) { 9 | 10 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) { 11 | // throw RuntimeException("DIFFERENT LENGTHS") 12 | // } 13 | // for (i in 0..MiniCalcLexer.serializedATN.length) { 14 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) { 15 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}") 16 | // } 17 | // } 18 | 19 | val input = ANTLRInputStream("1 + 2") 20 | val lexer = MiniCalcLexer(input) 21 | var token : Token? = null 22 | do { 23 | token = lexer.nextToken() 24 | println("TOKEN $token") 25 | 26 | } while (token?.type != -1) 27 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/main/kotlin/UsingParser.kt: -------------------------------------------------------------------------------- 1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream 2 | import org.antlr.v4.kotlinruntime.CharStream 3 | import org.antlr.v4.kotlinruntime.CommonTokenStream 4 | import org.antlr.v4.kotlinruntime.Token 5 | import java.lang.RuntimeException 6 | import me.tomassetti.minicalc.MiniCalcLexer 7 | import me.tomassetti.minicalc.MiniCalcParser 8 | 9 | fun main(args: Array) { 10 | 11 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) { 12 | // throw RuntimeException("DIFFERENT LENGTHS") 13 | // } 14 | // for (i in 0..MiniCalcLexer.serializedATN.length) { 15 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) { 16 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}") 17 | // } 18 | // } 19 | 20 | val input = ANTLRInputStream("input Int width\n") 21 | val lexer = MiniCalcLexer(input) 22 | var parser = MiniCalcParser(CommonTokenStream(lexer)) 23 | try { 24 | val root = parser.miniCalcFile() 25 | println("Parsed: ${root.javaClass}") 26 | println("Parsed: ${root.childCount}") 27 | println("Parsed: ${root.children!![0].javaClass}") 28 | } catch (e : Throwable) { 29 | println("Error: $e") 30 | } 31 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/test/kotlin/MiniCalcLexerTest.kt: -------------------------------------------------------------------------------- 1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream 2 | import org.antlr.v4.kotlinruntime.atn.EmptyPredictionContext 3 | import org.antlr.v4.kotlinruntime.atn.PredictionContext 4 | import kotlin.test.* 5 | import me.tomassetti.minicalc.MiniCalcLexer 6 | 7 | class TestingLexer { 8 | 9 | @Test fun firstTokenDebug1() { 10 | val input = ANTLRInputStream("1 + 2") 11 | val lexer = MiniCalcLexer(input) 12 | val interpreter = lexer.interpreter 13 | val result = interpreter!!.match(input, 0) 14 | assertEquals(11, result) 15 | } 16 | 17 | @Test fun checkMaxs() { 18 | assertEquals(2147483647, PredictionContext.EMPTY_RETURN_STATE) 19 | } 20 | 21 | @Test fun emptyPredictionContext() { 22 | assertEquals(true, EmptyPredictionContext().hasEmptyPath()) 23 | assertEquals(true, EmptyPredictionContext().isEmpty) 24 | } 25 | 26 | @Test fun firstTokenDebug2() { 27 | val input = ANTLRInputStream("1 + 2") 28 | val lexer = MiniCalcLexer(input) 29 | val interpreter = lexer.interpreter 30 | val decisionToDFA = interpreter!!.decisionToDFA 31 | val mode = 0 32 | val dfa = decisionToDFA[mode] 33 | assertEquals(true, dfa!!.s0 != null) 34 | assertEquals(0, dfa!!.s0!!.stateNumber) 35 | } 36 | 37 | @Test fun firstToken() { 38 | val input = ANTLRInputStream("1 + 2") 39 | val lexer = MiniCalcLexer(input) 40 | val token = lexer.nextToken() 41 | 42 | assertEquals("1", token.text) 43 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, token.type) 44 | } 45 | 46 | @Test fun simpleTokens() { 47 | val input = ANTLRInputStream("1 + 2") 48 | val lexer = MiniCalcLexer(input) 49 | val tokens = lexer.allTokens 50 | assertEquals(5, tokens.size) 51 | 52 | var i = 0 53 | assertEquals("1", tokens[i].text) 54 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type) 55 | 56 | i++ 57 | assertEquals(" ", tokens[i].text) 58 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type) 59 | 60 | i++ 61 | assertEquals("+", tokens[i].text) 62 | assertEquals(MiniCalcLexer.Tokens.PLUS.id, tokens[i].type) 63 | 64 | i++ 65 | assertEquals(" ", tokens[i].text) 66 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type) 67 | 68 | i++ 69 | assertEquals("2", tokens[i].text) 70 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type) 71 | } 72 | } -------------------------------------------------------------------------------- /antlr-kotlin-examples-jvm/src/test/kotlin/MiscStringTest.kt: -------------------------------------------------------------------------------- 1 | import com.strumenta.kotlinmultiplatform.toCharArray 2 | import kotlin.test.* 3 | 4 | fun assertArrayEquals(a: CharArray, b: CharArray) { 5 | assertEquals(a.size, b.size) 6 | for (i in 0..a.size) { 7 | assertEquals(a[i], b[i]) 8 | } 9 | } 10 | 11 | class MiscStringTest { 12 | 13 | // @Test fun testToCharArrayEmpty() { 14 | // assertArrayEquals(charArrayOf(), "".toCharArray()) 15 | // } 16 | 17 | @Test fun testToCharArrayEmptyLength() { 18 | assertEquals(0, "".toCharArray().size) 19 | } 20 | 21 | @Test fun testToCharArrayEmptyEl0() { 22 | assertEquals('a', "abc def".toCharArray()[0]) 23 | } 24 | 25 | // @Test fun testToCharArray() { 26 | // assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray()) 27 | // } 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = kotlinVersion 3 | 4 | repositories { 5 | mavenCentral() 6 | maven { 7 | url "https://plugins.gradle.org/m2/" 8 | } 9 | } 10 | dependencies { 11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 12 | } 13 | } 14 | 15 | apply plugin: 'org.jetbrains.kotlin.jvm' 16 | apply plugin: 'java-gradle-plugin' 17 | apply plugin: 'maven' 18 | 19 | group = projectGroup 20 | version = projectVersion 21 | 22 | repositories { 23 | jcenter() 24 | mavenLocal() 25 | } 26 | 27 | dependencies { 28 | compileOnly gradleApi() 29 | compileOnly "org.antlr:antlr4:${antlrVersion}@jar" 30 | compileOnly project(':antlr-kotlin-target') 31 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/AntlrSourceVirtualDirectory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin; 18 | 19 | import groovy.lang.Closure; 20 | import org.gradle.api.Action; 21 | import org.gradle.api.file.SourceDirectorySet; 22 | 23 | /** 24 | * Contract for a Gradle "convention object" that acts as a handler for what I call a virtual directory mapping, 25 | * injecting a virtual directory named 'antlr' into the project's various {@link org.gradle.api.tasks.SourceSet source 26 | * sets}. 27 | */ 28 | public interface AntlrSourceVirtualDirectory { 29 | String NAME = "antlr"; 30 | 31 | /** 32 | * All Antlr source for this source set. 33 | * 34 | * @return The Antlr source. Never returns null. 35 | */ 36 | SourceDirectorySet getAntlr(); 37 | 38 | /** 39 | * Configures the Antlr source for this set. The given closure is used to configure the {@link org.gradle.api.file.SourceDirectorySet} (see 40 | * {@link #getAntlr}) which contains the Antlr source. 41 | * 42 | * @param configureClosure The closure to use to configure the Antlr source. 43 | * @return this 44 | */ 45 | AntlrSourceVirtualDirectory antlr(Closure configureClosure); 46 | 47 | /** 48 | * Configures the Antlr source for this set. The given action is used to configure the {@link org.gradle.api.file.SourceDirectorySet} (see 49 | * {@link #getAntlr}) which contains the Antlr source. 50 | * 51 | * @param configureAction The action to use to configure the Antlr source. 52 | * @return this 53 | * @since 3.5 54 | */ 55 | AntlrSourceVirtualDirectory antlr(Action configureAction); 56 | } 57 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin.internal; 18 | 19 | import java.io.Serializable; 20 | 21 | public class AntlrResult implements Serializable { 22 | 23 | private final int errorCount; 24 | private final Exception exception; 25 | 26 | public AntlrResult(int errorCount) { 27 | this(errorCount, null); 28 | } 29 | public AntlrResult(int errorCount, Exception exception) { 30 | this.errorCount = errorCount; 31 | this.exception = exception; 32 | } 33 | 34 | public int getErrorCount() { 35 | return errorCount; 36 | } 37 | 38 | public Exception getException() { 39 | return exception; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSourceGenerationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin.internal; 18 | 19 | import org.gradle.api.GradleException; 20 | import org.gradle.internal.exceptions.Contextual; 21 | 22 | @Contextual 23 | public class AntlrSourceGenerationException extends GradleException { 24 | public AntlrSourceGenerationException(String message, Throwable cause) { 25 | super(message, cause); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSourceVirtualDirectoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.strumenta.antlrkotlin.gradleplugin.internal; 17 | 18 | import groovy.lang.Closure; 19 | import org.gradle.api.Action; 20 | import org.gradle.api.file.SourceDirectorySet; 21 | import org.gradle.api.internal.file.SourceDirectorySetFactory; 22 | import org.gradle.api.plugins.antlr.AntlrSourceVirtualDirectory; 23 | import org.gradle.util.ConfigureUtil; 24 | 25 | /** 26 | * The implementation of the {@link org.gradle.api.plugins.antlr.AntlrSourceVirtualDirectory} contract. 27 | */ 28 | public class AntlrSourceVirtualDirectoryImpl implements AntlrSourceVirtualDirectory { 29 | private final SourceDirectorySet antlr; 30 | 31 | public AntlrSourceVirtualDirectoryImpl(String parentDisplayName, SourceDirectorySetFactory sourceDirectorySetFactory) { 32 | final String displayName = parentDisplayName + " Antlr source"; 33 | antlr = sourceDirectorySetFactory.create(displayName); 34 | antlr.getFilter().include("**/*.g"); 35 | antlr.getFilter().include("**/*.g4"); 36 | } 37 | 38 | @Override 39 | public SourceDirectorySet getAntlr() { 40 | return antlr; 41 | } 42 | 43 | @Override 44 | public AntlrSourceVirtualDirectory antlr(Closure configureClosure) { 45 | ConfigureUtil.configure(configureClosure, getAntlr()); 46 | return this; 47 | } 48 | 49 | @Override 50 | public AntlrSourceVirtualDirectory antlr(Action configureAction) { 51 | configureAction.execute(getAntlr()); 52 | return this; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSpec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin.internal; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.LinkedList; 22 | import java.util.List; 23 | import java.util.Set; 24 | 25 | public class AntlrSpec implements Serializable { 26 | 27 | private List arguments; 28 | private Set inputDirectories; 29 | private Set grammarFiles; 30 | private String maxHeapSize; 31 | private File outputDirectory; 32 | 33 | public AntlrSpec(List arguments, Set grammarFiles, Set inputDirectories, File outputDirectory, String maxHeapSize) { 34 | this.arguments = arguments; 35 | this.inputDirectories = inputDirectories; 36 | this.grammarFiles = grammarFiles; 37 | this.outputDirectory = outputDirectory; 38 | this.maxHeapSize = maxHeapSize; 39 | } 40 | 41 | public List getArguments() { 42 | return arguments; 43 | } 44 | 45 | public Set getGrammarFiles() { 46 | return grammarFiles; 47 | } 48 | 49 | public String getMaxHeapSize() { 50 | return maxHeapSize; 51 | } 52 | 53 | public File getOutputDirectory() { 54 | return outputDirectory; 55 | } 56 | 57 | public List asArgumentsWithFiles() { 58 | List commandLine = new LinkedList<>(arguments); 59 | commandLine.add("-o"); 60 | commandLine.add(getOutputDirectory().getAbsolutePath()); 61 | for (File file : getGrammarFiles()) { 62 | commandLine.add(file.getAbsolutePath()); 63 | } 64 | 65 | return commandLine; 66 | } 67 | 68 | public Set getInputDirectories() { 69 | return inputDirectories; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSpecFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin.internal; 18 | 19 | import org.gradle.api.file.SourceDirectorySet; 20 | import com.strumenta.antlrkotlin.gradleplugin.AntlrKotlinTask; 21 | 22 | import java.io.File; 23 | import java.util.LinkedList; 24 | import java.util.List; 25 | import java.util.Set; 26 | 27 | public class AntlrSpecFactory { 28 | 29 | public AntlrSpec create(AntlrKotlinTask antlrTask, Set grammarFiles, 30 | SourceDirectorySet sourceDirectorySet) { 31 | List arguments = new LinkedList<>(antlrTask.getArguments()); 32 | 33 | if (antlrTask.isTrace() && !arguments.contains("-trace")) { 34 | arguments.add("-trace"); 35 | } 36 | if (antlrTask.isTraceLexer() && !arguments.contains("-traceLexer")) { 37 | arguments.add("-traceLexer"); 38 | } 39 | if (antlrTask.isTraceParser() && !arguments.contains("-traceParser")) { 40 | arguments.add("-traceParser"); 41 | } 42 | if (antlrTask.isTraceTreeWalker() && !arguments.contains("-traceTreeWalker")) { 43 | arguments.add("-traceTreeWalker"); 44 | } 45 | 46 | return new AntlrSpec(arguments, grammarFiles, sourceDirectorySet.getSrcDirs(), antlrTask.getOutputDirectory(), 47 | antlrTask.getMaxHeapSize()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrWorker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.strumenta.antlrkotlin.gradleplugin.internal; 18 | 19 | public interface AntlrWorker { 20 | AntlrResult runAntlr(AntlrSpec spec); 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * A {@link org.gradle.api.Plugin} for generating parsers from Antlr grammars using the Kotlin target. 19 | */ 20 | package com.strumenta.antlrkotlin.gradleplugin; 21 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/resources/META-INF/gradle-plugins/com.strumenta.antlrkotlin.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.strumenta.antlrkotlin.gradleplugin.AntlrKotlinPlugin 2 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = kotlinVersion 3 | 4 | repositories { 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 9 | } 10 | } 11 | 12 | apply plugin: 'kotlin-platform-common' 13 | apply plugin: 'maven' 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | group = projectGroup 20 | version = projectVersion 21 | 22 | dependencies { 23 | compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion" 24 | testCompile "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlinVersion" 25 | testCompile "org.jetbrains.kotlin:kotlin-test-common:$kotlinVersion" 26 | testCompile "junit:junit:4.12" 27 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion" 28 | } 29 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ANTLRFileStream.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | import org.antlr.v4.kotlinruntime.misc.Utils 9 | 10 | ///** 11 | // * This is an [ANTLRInputStream] that is loaded from a file all at once 12 | // * when you construct the object. 13 | // * 14 | // */ 15 | //@Deprecated("as of 4.7 Please use {@link CharStreams} interface.") 16 | //class ANTLRFileStream constructor(fileName: String, encoding: String? = null) : ANTLRInputStream() { 17 | // override var sourceName: String 18 | // protected set 19 | // 20 | // init { 21 | // this.sourceName = fileName 22 | // load(fileName, encoding) 23 | // } 24 | // 25 | // fun load(fileName: String, encoding: String?) { 26 | // data = Utils.readFile(fileName, encoding) 27 | // this.n = data.size 28 | // } 29 | //} 30 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/BaseErrorListener.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | import com.strumenta.kotlinmultiplatform.BitSet 9 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 10 | import org.antlr.v4.kotlinruntime.dfa.DFA 11 | 12 | /** 13 | * Provides an empty default implementation of [ANTLRErrorListener]. The 14 | * default implementation of each method does nothing, but can be overridden as 15 | * necessary. 16 | * 17 | * @author Sam Harwell 18 | */ 19 | open class BaseErrorListener : ANTLRErrorListener { 20 | override fun syntaxError(recognizer: Recognizer<*, *>, 21 | offendingSymbol: Any?, 22 | line: Int, 23 | charPositionInLine: Int, 24 | msg: String, 25 | e: RecognitionException?) { 26 | } 27 | 28 | override fun reportAmbiguity(recognizer: Parser, 29 | dfa: DFA, 30 | startIndex: Int, 31 | stopIndex: Int, 32 | exact: Boolean, 33 | ambigAlts: BitSet, 34 | configs: ATNConfigSet) { 35 | } 36 | 37 | override fun reportAttemptingFullContext(recognizer: Parser, 38 | dfa: DFA, 39 | startIndex: Int, 40 | stopIndex: Int, 41 | conflictingAlts: BitSet, 42 | configs: ATNConfigSet) { 43 | } 44 | 45 | override fun reportContextSensitivity(recognizer: Parser, 46 | dfa: DFA, 47 | startIndex: Int, 48 | stopIndex: Int, 49 | prediction: Int, 50 | configs: ATNConfigSet) { 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/CharStream.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime 8 | 9 | import org.antlr.v4.kotlinruntime.misc.Interval 10 | 11 | /** A source of characters for an ANTLR lexer. */ 12 | interface CharStream : 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 [IntStream.mark]. 18 | * 19 | * @param interval an interval within the stream 20 | * @return the text of the specified interval 21 | * 22 | * @throws NullPointerException if `interval` is `null` 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 | fun getText(interval: Interval): String 30 | 31 | companion object { 32 | val EOF = IntStream.EOF 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ConsoleErrorListener.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | import com.strumenta.kotlinmultiplatform.errMessage 9 | 10 | /** 11 | * 12 | * @author Sam Harwell 13 | */ 14 | class ConsoleErrorListener : BaseErrorListener() { 15 | 16 | /** 17 | * {@inheritDoc} 18 | * 19 | * 20 | * 21 | * This implementation prints messages to [System.err] containing the 22 | * values of `line`, `charPositionInLine`, and `msg` using 23 | * the following format. 24 | * 25 | *
26 |      * line *line*:*charPositionInLine* *msg*
27 |     
* 28 | */ 29 | override fun syntaxError(recognizer: Recognizer<*, *>, 30 | offendingSymbol: Any?, 31 | line: Int, 32 | charPositionInLine: Int, 33 | msg: String, 34 | e: RecognitionException?) { 35 | errMessage("line $line:$charPositionInLine $msg") 36 | } 37 | 38 | companion object { 39 | /** 40 | * Provides a default instance of [ConsoleErrorListener]. 41 | */ 42 | val INSTANCE = ConsoleErrorListener() 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/FailedPredicateException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | import org.antlr.v4.kotlinruntime.atn.AbstractPredicateTransition 9 | import org.antlr.v4.kotlinruntime.atn.PredicateTransition 10 | 11 | 12 | private fun formatMessage(predicate: String?, message: String?): String { 13 | return message ?: "failed predicate: {$predicate}?" 14 | 15 | } 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 | class FailedPredicateException constructor(recognizer: Parser, 23 | val predicate: String? = null, 24 | message: String? = null) : RecognitionException(recognizer, recognizer.readInputStream()!!, recognizer.context!!, formatMessage(predicate, message)) { 25 | var ruleIndex: Int = -1 26 | var predIndex: Int = -1 27 | 28 | init { 29 | val s = recognizer.interpreter!!.atn.states.get(recognizer.state) 30 | 31 | val trans = s!!.transition(0) as AbstractPredicateTransition 32 | if (trans is PredicateTransition) { 33 | this.ruleIndex = (trans as PredicateTransition).ruleIndex 34 | this.predIndex = (trans as PredicateTransition).predIndex 35 | } else { 36 | this.ruleIndex = 0 37 | this.predIndex = 0 38 | } 39 | TODO() 40 | //this.offendingToken = recognizer.currentToken 41 | } 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/InputMismatchException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | /** This signifies any kind of mismatched input exceptions such as 9 | * when the current input does not match the expected token. 10 | */ 11 | class InputMismatchException : RecognitionException { 12 | constructor(recognizer: Parser) : super(recognizer, recognizer.readInputStream()!!, recognizer.context!!) { 13 | this.offendingToken = recognizer.currentToken 14 | } 15 | 16 | constructor(recognizer: Parser, state: Int, ctx: ParserRuleContext) : super(recognizer, recognizer.readInputStream()!!, ctx) { 17 | this.offendingState = state 18 | this.offendingToken = recognizer.currentToken 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/InterpreterRuleContext.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | /** 9 | * This class extends [ParserRuleContext] by allowing the value of 10 | * [.getRuleIndex] to be explicitly set for the context. 11 | * 12 | * 13 | * 14 | * [ParserRuleContext] does not include field storage for the rule index 15 | * since the context classes created by the code generator override the 16 | * [.getRuleIndex] method to return the correct value for that context. 17 | * Since the parser interpreter does not use the context classes generated for a 18 | * parser, this class (with slightly more memory overhead per node) is used to 19 | * provide equivalent functionality. 20 | */ 21 | class InterpreterRuleContext : ParserRuleContext { 22 | /** This is the backing field for [.getRuleIndex]. */ 23 | override var ruleIndex = -1 24 | set(value: Int) { 25 | super.ruleIndex = value 26 | } 27 | 28 | constructor() {} 29 | 30 | /** 31 | * Constructs a new [InterpreterRuleContext] with the specified 32 | * parent, invoking state, and rule index. 33 | * 34 | * @param parent The parent context. 35 | * @param invokingStateNumber The invoking state number. 36 | * @param ruleIndex The rule index for the current context. 37 | */ 38 | constructor(parent: ParserRuleContext, 39 | invokingStateNumber: Int, 40 | ruleIndex: Int) : super(parent, invokingStateNumber) { 41 | this.ruleIndex = ruleIndex 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/LexerNoViableAltException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime 8 | 9 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 10 | import org.antlr.v4.kotlinruntime.misc.Interval 11 | import org.antlr.v4.kotlinruntime.misc.Utils 12 | 13 | class LexerNoViableAltException(lexer: Lexer, 14 | input: CharStream, 15 | /** Matching attempted at what input index? */ 16 | val startIndex: Int, 17 | /** Which configurations did we try at input.index() that couldn't match input.LA(1)? */ 18 | val deadEndConfigs: ATNConfigSet) : RecognitionException(lexer, input, null) { 19 | 20 | override val inputStream: CharStream 21 | get() = super.inputStream as CharStream 22 | 23 | override fun toString(): String { 24 | var symbol = "" 25 | if (startIndex >= 0 && startIndex < inputStream.size()) { 26 | symbol = inputStream.getText(Interval.of(startIndex, startIndex)) 27 | symbol = Utils.escapeWhitespace(symbol, false) 28 | } 29 | 30 | return "LexerNoViableAltException('$symbol')" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/NoViableAltException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime 7 | 8 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 9 | 10 | /** Indicates that the parser could not decide which of two or more paths 11 | * to take based upon the remaining input. It tracks the starting token 12 | * of the offending input and also knows where the parser was 13 | * in the various paths when the error. Reported by reportNoViableAlternative() 14 | */ 15 | class NoViableAltException constructor(recognizer: Parser, 16 | input: TokenStream? = recognizer.readInputStream() as TokenStream?, 17 | /** The token object at the start index; the input stream might 18 | * not be buffering tokens so get a reference to it. (At the 19 | * time the error occurred, of course the stream needs to keep a 20 | * buffer all of the tokens but later we might not have access to those.) 21 | */ 22 | 23 | val startToken: Token? = recognizer.currentToken, 24 | offendingToken: Token? = recognizer.currentToken, 25 | /** Which configurations did we try at input.index() that couldn't match input.LT(1)? */ 26 | 27 | val deadEndConfigs: ATNConfigSet? = null, 28 | ctx: ParserRuleContext? = recognizer.context) : RecognitionException(recognizer, input!!, ctx!!) { 29 | 30 | init { 31 | this.offendingToken = offendingToken 32 | } 33 | 34 | }// LL(1) error 35 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/RuleContextWithAltNum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime 8 | 9 | import org.antlr.v4.kotlinruntime.atn.ATN 10 | 11 | /** A handy class for use with 12 | * 13 | * options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;} 14 | * 15 | * that provides a backing field / impl for the outer alternative number 16 | * matched for an internal parse tree node. 17 | * 18 | * I'm only putting into Java runtime as I'm certain I'm the only one that 19 | * will really every use this. 20 | */ 21 | class RuleContextWithAltNum : ParserRuleContext { 22 | override var altNumber: Int = 0 23 | 24 | constructor() { 25 | altNumber = ATN.INVALID_ALT_NUMBER 26 | } 27 | 28 | constructor(parent: ParserRuleContext, invokingStateNumber: Int) : super(parent, invokingStateNumber) {} 29 | } 30 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/TokenFactory.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime 8 | 9 | import org.antlr.v4.kotlinruntime.misc.Pair 10 | 11 | /** The default mechanism for creating tokens. It's used by default in Lexer and 12 | * the error handling strategy (to create missing tokens). Notifying the parser 13 | * of a new factory means that it notifies its token source and error strategy. 14 | */ 15 | interface TokenFactory { 16 | /** This is the method used to create tokens in the lexer and in the 17 | * error handling strategy. If text!=null, than the start and stop positions 18 | * are wiped to -1 in the text override is set in the CommonToken. 19 | */ 20 | fun create(source: Pair, type: Int, text: String?, 21 | channel: Int, start: Int, stop: Int, 22 | line: Int, charPositionInLine: Int): Symbol 23 | 24 | /** Generically useful */ 25 | fun create(type: Int, text: String): Symbol 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/WritableToken.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime 8 | 9 | interface WritableToken : Token { 10 | 11 | override var text: String? 12 | 13 | 14 | /** Get the token type of the token */ 15 | override var type: Int 16 | 17 | /** The line number on which the 1st character of this token was matched, 18 | * line=1..n 19 | */ 20 | override var line: Int 21 | 22 | /** The index of the first character of this token relative to the 23 | * beginning of the line at which it occurs, 0..n-1 24 | */ 25 | override var charPositionInLine: Int 26 | 27 | /** Return the channel this token. Each token can arrive at the parser 28 | * on a different channel, but the parser only "tunes" to a single channel. 29 | * The parser ignores everything not on DEFAULT_CHANNEL. 30 | */ 31 | override var channel: Int 32 | 33 | /** An index from 0..n-1 of the token object in the input stream. 34 | * This must be valid in order to print token streams and 35 | * use TokenRewriteStream. 36 | * 37 | * Return -1 to indicate that this token was conjured up since 38 | * it doesn't have a valid index. 39 | */ 40 | override var tokenIndex: Int 41 | } 42 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ast/Node.kt: -------------------------------------------------------------------------------- 1 | package org.antlr.v4.kotlinruntime.ast 2 | 3 | /** 4 | * The Abstract Syntax Tree will be constituted by instances of Node. 5 | */ 6 | interface Node { 7 | val parent: Node? 8 | val position: Position? 9 | } 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ATNDeserializationOptions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * 11 | * @author Sam Harwell 12 | */ 13 | class ATNDeserializationOptions { 14 | 15 | var isReadOnly: Boolean = false 16 | private set 17 | private var verifyATN: Boolean = false 18 | private var generateRuleBypassTransitions: Boolean = false 19 | 20 | var isVerifyATN: Boolean 21 | get() = verifyATN 22 | set(verifyATN) { 23 | throwIfReadOnly() 24 | this.verifyATN = verifyATN 25 | } 26 | 27 | var isGenerateRuleBypassTransitions: Boolean 28 | get() = generateRuleBypassTransitions 29 | set(generateRuleBypassTransitions) { 30 | throwIfReadOnly() 31 | this.generateRuleBypassTransitions = generateRuleBypassTransitions 32 | } 33 | 34 | constructor() { 35 | this.verifyATN = true 36 | this.generateRuleBypassTransitions = false 37 | } 38 | 39 | constructor(options: ATNDeserializationOptions) { 40 | this.verifyATN = options.verifyATN 41 | this.generateRuleBypassTransitions = options.generateRuleBypassTransitions 42 | } 43 | 44 | fun makeReadOnly() { 45 | isReadOnly = true 46 | } 47 | 48 | protected fun throwIfReadOnly() { 49 | if (isReadOnly) { 50 | throw IllegalStateException("The object is read only.") 51 | } 52 | } 53 | 54 | companion object { 55 | val defaultOptions: ATNDeserializationOptions 56 | 57 | init { 58 | defaultOptions = ATNDeserializationOptions() 59 | defaultOptions.makeReadOnly() 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ATNType.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * Represents the type of recognizer an ATN applies to. 11 | * 12 | * @author Sam Harwell 13 | */ 14 | enum class ATNType { 15 | 16 | /** 17 | * A lexer grammar. 18 | */ 19 | LEXER, 20 | 21 | /** 22 | * A parser grammar. 23 | */ 24 | PARSER 25 | 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/AbstractPredicateTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * 11 | * @author Sam Harwell 12 | */ 13 | abstract class AbstractPredicateTransition(target: ATNState) : Transition(target) 14 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ActionTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class ActionTransition constructor(target: ATNState, val ruleIndex: Int, val actionIndex: Int = -1, val isCtxDependent: Boolean = false // e.g., $i ref in action 10 | ) : Transition(target) { 11 | 12 | override val serializationType: Int 13 | get() = Transition.ACTION 14 | 15 | override// we are to be ignored by analysis 'cept for predicates 16 | val isEpsilon: Boolean 17 | get() = true 18 | 19 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 20 | return false 21 | } 22 | 23 | override fun toString(): String { 24 | return "action_$ruleIndex:$actionIndex" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/AtomTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 10 | 11 | /** TODO: make all transitions sets? no, should remove set edges */ 12 | class AtomTransition(target: ATNState, 13 | /** The token type or character value; or, signifies special accessLabel. */ 14 | val label: Int) : Transition(target) { 15 | 16 | override val serializationType: Int 17 | get() = Transition.ATOM 18 | 19 | override fun accessLabel(): IntervalSet? { 20 | return IntervalSet.of(label) 21 | } 22 | 23 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 24 | return label == symbol 25 | } 26 | 27 | override fun toString(): String { 28 | return label.toString() 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BasicBlockStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * 11 | * @author Sam Harwell 12 | */ 13 | class BasicBlockStartState : BlockStartState() { 14 | override val stateType: Int 15 | get() = ATNState.BLOCK_START 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BasicState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * 11 | * @author Sam Harwell 12 | */ 13 | class BasicState : ATNState() { 14 | 15 | override val stateType: Int 16 | get() = ATNState.BASIC 17 | 18 | } 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BlockEndState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** Terminal node of a simple `(a|b|c)` block. */ 10 | class BlockEndState : ATNState() { 11 | var startState: BlockStartState? = null 12 | 13 | override val stateType: Int 14 | get() = ATNState.BLOCK_END 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BlockStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** The start of a regular `(...)` block. */ 10 | abstract class BlockStartState : DecisionState() { 11 | var endState: BlockEndState? = null 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/CodePointTransitions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import com.strumenta.kotlinmultiplatform.isSupplementaryCodePoint 10 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 11 | 12 | /** 13 | * Utility class to create [AtomTransition], [RangeTransition], 14 | * and [SetTransition] appropriately based on the range of the input. 15 | * 16 | * To keep the serialized ATN size small, we only inline atom and 17 | * range transitions for Unicode code points <= U+FFFF. 18 | * 19 | * Whenever we encounter a Unicode code point > U+FFFF, we represent that 20 | * as a set transition (even if it is logically an atom or a range). 21 | */ 22 | object CodePointTransitions { 23 | /** 24 | * If `codePoint` is <= U+FFFF, returns a new [AtomTransition]. 25 | * Otherwise, returns a new [SetTransition]. 26 | */ 27 | fun createWithCodePoint(target: ATNState, codePoint: Int): Transition { 28 | return if (Char.isSupplementaryCodePoint(codePoint)) { 29 | SetTransition(target, IntervalSet.of(codePoint)) 30 | } else { 31 | AtomTransition(target, codePoint) 32 | } 33 | } 34 | 35 | /** 36 | * If `codePointFrom` and `codePointTo` are both 37 | * <= U+FFFF, returns a new [RangeTransition]. 38 | * Otherwise, returns a new [SetTransition]. 39 | */ 40 | fun createWithCodePointRange( 41 | target: ATNState, 42 | codePointFrom: Int, 43 | codePointTo: Int): Transition { 44 | return if (Char.isSupplementaryCodePoint(codePointFrom) || Char.isSupplementaryCodePoint(codePointTo)) { 45 | SetTransition(target, IntervalSet.of(codePointFrom, codePointTo)) 46 | } else { 47 | RangeTransition(target, codePointFrom, codePointTo) 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ContextSensitivityInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.ANTLRErrorListener 10 | import org.antlr.v4.kotlinruntime.TokenStream 11 | 12 | /** 13 | * This class represents profiling event information for a context sensitivity. 14 | * Context sensitivities are decisions where a particular input resulted in an 15 | * SLL conflict, but LL prediction produced a single unique alternative. 16 | * 17 | * 18 | * 19 | * In some cases, the unique alternative identified by LL prediction is not 20 | * equal to the minimum represented alternative in the conflicting SLL 21 | * configuration set. Grammars and inputs which result in this scenario are 22 | * unable to use [PredictionMode.SLL], which in turn means they cannot use 23 | * the two-stage parsing strategy to improve parsing performance for that 24 | * input. 25 | * 26 | * @see ParserATNSimulator.reportContextSensitivity 27 | * 28 | * @see ANTLRErrorListener.reportContextSensitivity 29 | * 30 | * 31 | * @since 4.3 32 | */ 33 | class ContextSensitivityInfo 34 | /** 35 | * Constructs a new instance of the [ContextSensitivityInfo] class 36 | * with the specified detailed context sensitivity information. 37 | * 38 | * @param decision The decision number 39 | * @param configs The final configuration set containing the unique 40 | * alternative identified by full-context prediction 41 | * @param input The input token stream 42 | * @param startIndex The start index for the current prediction 43 | * @param stopIndex The index at which the context sensitivity was 44 | * identified during full-context prediction 45 | */ 46 | (decision: Int, 47 | configs: ATNConfigSet, 48 | input: TokenStream, startIndex: Int, stopIndex: Int) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, true) 49 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/DecisionEventInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.TokenStream 10 | 11 | /** 12 | * This is the base class for gathering detailed information about prediction 13 | * events which occur during parsing. 14 | * 15 | * Note that we could record the parser call stack at the time this event 16 | * occurred but in the presence of left recursive rules, the stack is kind of 17 | * meaningless. It's better to look at the individual configurations for their 18 | * individual stacks. Of course that is a [PredictionContext] object 19 | * not a parse tree node and so it does not have information about the extent 20 | * (start...stop) of the various subtrees. Examining the stack tops of all 21 | * configurations provide the return states for the rule invocations. 22 | * From there you can get the enclosing rule. 23 | * 24 | * @since 4.3 25 | */ 26 | open class DecisionEventInfo( 27 | /** 28 | * The invoked decision number which this event is related to. 29 | * 30 | * @see ATN.decisionToState 31 | */ 32 | val decision: Int, 33 | /** 34 | * The configuration set containing additional information relevant to the 35 | * prediction state when the current event occurred, or `null` if no 36 | * additional information is relevant or available. 37 | */ 38 | val configs: ATNConfigSet, 39 | /** 40 | * The input token stream which is being parsed. 41 | */ 42 | val input: TokenStream, 43 | /** 44 | * The token index in the input stream at which the current prediction was 45 | * originally invoked. 46 | */ 47 | val startIndex: Int, 48 | /** 49 | * The token index in the input stream at which the current event occurred. 50 | */ 51 | val stopIndex: Int, 52 | /** 53 | * `true` if the current event occurred during LL prediction; 54 | * otherwise, `false` if the input occurred during SLL prediction. 55 | */ 56 | val fullCtx: Boolean) 57 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/DecisionState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | abstract class DecisionState : ATNState() { 10 | var decision = -1 11 | var nonGreedy: Boolean = false 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/EmptyPredictionContext.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class EmptyPredictionContext : SingletonPredictionContext(null, PredictionContext.EMPTY_RETURN_STATE) { 10 | 11 | override val isEmpty: Boolean 12 | get() = true 13 | 14 | override fun size(): Int { 15 | return 1 16 | } 17 | 18 | override fun getParent(index: Int): PredictionContext? { 19 | return null 20 | } 21 | 22 | override fun getReturnState(index: Int): Int { 23 | // It was: return returnState 24 | // Changed because of https://youtrack.jetbrains.com/issue/KT-22161 25 | return PredictionContext.EMPTY_RETURN_STATE 26 | } 27 | 28 | override fun equals(o: Any?): Boolean { 29 | return this === o 30 | } 31 | 32 | override fun toString(): String { 33 | return "$" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/EpsilonTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class EpsilonTransition constructor(target: ATNState, private val outermostPrecedenceReturn: Int = -1) : Transition(target) { 10 | 11 | override val serializationType: Int 12 | get() = Transition.EPSILON 13 | 14 | override val isEpsilon: Boolean 15 | get() = true 16 | 17 | /** 18 | * @return the rule index of a precedence rule for which this transition is 19 | * returning from, where the precedence value is 0; otherwise, -1. 20 | * 21 | * @see ATNConfig.isPrecedenceFilterSuppressed 22 | * @see ParserATNSimulator.applyPrecedenceFilter 23 | * @since 4.4.1 24 | */ 25 | fun outermostPrecedenceReturn(): Int { 26 | return outermostPrecedenceReturn 27 | } 28 | 29 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 30 | return false 31 | } 32 | 33 | override fun toString(): String { 34 | return "epsilon" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ErrorInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.* 10 | 11 | /** 12 | * This class represents profiling event information for a syntax error 13 | * identified during prediction. Syntax errors occur when the prediction 14 | * algorithm is unable to identify an alternative which would lead to a 15 | * successful parse. 16 | * 17 | * @see Parser.notifyErrorListeners 18 | * @see ANTLRErrorListener.syntaxError 19 | * 20 | * 21 | * @since 4.3 22 | */ 23 | class ErrorInfo 24 | /** 25 | * Constructs a new instance of the [ErrorInfo] class with the 26 | * specified detailed syntax error information. 27 | * 28 | * @param decision The decision number 29 | * @param configs The final configuration set reached during prediction 30 | * prior to reaching the [ATNSimulator.ERROR] state 31 | * @param input The input token stream 32 | * @param startIndex The start index for the current prediction 33 | * @param stopIndex The index at which the syntax error was identified 34 | * @param fullCtx `true` if the syntax error was identified during LL 35 | * prediction; otherwise, `false` if the syntax error was identified 36 | * during SLL prediction 37 | */ 38 | (decision: Int, 39 | configs: ATNConfigSet, 40 | input: TokenStream, startIndex: Int, stopIndex: Int, 41 | fullCtx: Boolean) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) 42 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.CharStream 10 | import org.antlr.v4.kotlinruntime.Lexer 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 | interface LexerAction { 21 | /** 22 | * Gets the serialization type of the lexer action. 23 | * 24 | * @return The serialization type of the lexer action. 25 | */ 26 | val actionType: LexerActionType 27 | 28 | /** 29 | * Gets whether the lexer action is position-dependent. Position-dependent 30 | * actions may have different semantics depending on the [CharStream] 31 | * index at the time the action is executed. 32 | * 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 [LexerATNConfig.lexerActionExecutor]. 38 | * 39 | * @return `true` if the lexer action semantics can be affected by the 40 | * position of the input [CharStream] at the time it is executed; 41 | * otherwise, `false`. 42 | */ 43 | val isPositionDependent: Boolean 44 | 45 | /** 46 | * Execute the lexer action in the context of the specified [Lexer]. 47 | * 48 | * 49 | * For position-dependent actions, the input stream must already be 50 | * positioned correctly prior to calling this method. 51 | * 52 | * @param lexer The lexer instance. 53 | */ 54 | fun execute(lexer: Lexer) 55 | } 56 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerActionType.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * Represents the serialization type of a [LexerAction]. 11 | * 12 | * @author Sam Harwell 13 | * @since 4.2 14 | */ 15 | enum class LexerActionType { 16 | /** 17 | * The type of a [LexerChannelAction] action. 18 | */ 19 | CHANNEL, 20 | /** 21 | * The type of a [LexerCustomAction] action. 22 | */ 23 | CUSTOM, 24 | /** 25 | * The type of a [LexerModeAction] action. 26 | */ 27 | MODE, 28 | /** 29 | * The type of a [LexerMoreAction] action. 30 | */ 31 | MORE, 32 | /** 33 | * The type of a [LexerPopModeAction] action. 34 | */ 35 | POP_MODE, 36 | /** 37 | * The type of a [LexerPushModeAction] action. 38 | */ 39 | PUSH_MODE, 40 | /** 41 | * The type of a [LexerSkipAction] action. 42 | */ 43 | SKIP, 44 | /** 45 | * The type of a [LexerTypeAction] action. 46 | */ 47 | TYPE 48 | } 49 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerChannelAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | import org.antlr.v4.kotlinruntime.Token 12 | 13 | /** 14 | * Implements the `channel` lexer action by calling 15 | * [Lexer.setChannel] with the assigned channel. 16 | * 17 | * @author Sam Harwell 18 | * @since 4.2 19 | */ 20 | class LexerChannelAction 21 | /** 22 | * Constructs a new `channel` action with the specified channel value. 23 | * @param channel The channel value to pass to [Lexer.setChannel]. 24 | */ 25 | ( 26 | /** 27 | * Gets the channel to use for the [Token] created by the lexer. 28 | * 29 | * @return The channel to use for the [Token] created by the lexer. 30 | */ 31 | val channel: Int) : LexerAction { 32 | 33 | /** 34 | * {@inheritDoc} 35 | * @return This method returns [LexerActionType.CHANNEL]. 36 | */ 37 | override val actionType: LexerActionType 38 | get() = LexerActionType.CHANNEL 39 | 40 | /** 41 | * {@inheritDoc} 42 | * @return This method returns `false`. 43 | */ 44 | override val isPositionDependent: Boolean 45 | get() = false 46 | 47 | /** 48 | * {@inheritDoc} 49 | * 50 | * 51 | * This action is implemented by calling [Lexer.setChannel] with the 52 | * value provided by [.getChannel]. 53 | */ 54 | override fun execute(lexer: Lexer) { 55 | lexer.channel = channel 56 | } 57 | 58 | override fun hashCode(): Int { 59 | var hash = MurmurHash.initialize() 60 | hash = MurmurHash.update(hash, actionType.ordinal) 61 | hash = MurmurHash.update(hash, channel) 62 | return MurmurHash.finish(hash, 2) 63 | } 64 | 65 | override fun equals(obj: Any?): Boolean { 66 | if (obj === this) { 67 | return true 68 | } else if (obj !is LexerChannelAction) { 69 | return false 70 | } 71 | 72 | return channel == obj.channel 73 | } 74 | 75 | override fun toString(): String { 76 | return "channel($channel)" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerModeAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `mode` lexer action by calling [Lexer.mode] with 14 | * the assigned mode. 15 | * 16 | * @author Sam Harwell 17 | * @since 4.2 18 | */ 19 | class LexerModeAction 20 | /** 21 | * Constructs a new `mode` action with the specified mode value. 22 | * @param mode The mode value to pass to [Lexer.mode]. 23 | */ 24 | ( 25 | /** 26 | * Get the lexer mode this action should transition the lexer to. 27 | * 28 | * @return The lexer mode for this `mode` command. 29 | */ 30 | val mode: Int) : LexerAction { 31 | 32 | /** 33 | * {@inheritDoc} 34 | * @return This method returns [LexerActionType.MODE]. 35 | */ 36 | override val actionType: LexerActionType 37 | get() = LexerActionType.MODE 38 | 39 | /** 40 | * {@inheritDoc} 41 | * @return This method returns `false`. 42 | */ 43 | override val isPositionDependent: Boolean 44 | get() = false 45 | 46 | /** 47 | * {@inheritDoc} 48 | * 49 | * 50 | * This action is implemented by calling [Lexer.mode] with the 51 | * value provided by [.getMode]. 52 | */ 53 | override fun execute(lexer: Lexer) { 54 | lexer.mode(mode) 55 | } 56 | 57 | override fun hashCode(): Int { 58 | var hash = MurmurHash.initialize() 59 | hash = MurmurHash.update(hash, actionType.ordinal) 60 | hash = MurmurHash.update(hash, mode) 61 | return MurmurHash.finish(hash, 2) 62 | } 63 | 64 | override fun equals(obj: Any?): Boolean { 65 | if (obj === this) { 66 | return true 67 | } else if (obj !is LexerModeAction) { 68 | return false 69 | } 70 | 71 | return mode == obj.mode 72 | } 73 | 74 | override fun toString(): String { 75 | return "mode($mode)" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerMoreAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `more` lexer action by calling [Lexer.more]. 14 | * 15 | * 16 | * The `more` command does not have any parameters, so this action is 17 | * implemented as a singleton instance exposed by [.INSTANCE]. 18 | * 19 | * @author Sam Harwell 20 | * @since 4.2 21 | */ 22 | class LexerMoreAction 23 | /** 24 | * Constructs the singleton instance of the lexer `more` command. 25 | */ 26 | private constructor() : LexerAction { 27 | 28 | /** 29 | * {@inheritDoc} 30 | * @return This method returns [LexerActionType.MORE]. 31 | */ 32 | override val actionType: LexerActionType 33 | get() = LexerActionType.MORE 34 | 35 | /** 36 | * {@inheritDoc} 37 | * @return This method returns `false`. 38 | */ 39 | override val isPositionDependent: Boolean 40 | get() = false 41 | 42 | /** 43 | * {@inheritDoc} 44 | * 45 | * 46 | * This action is implemented by calling [Lexer.more]. 47 | */ 48 | override fun execute(lexer: Lexer) { 49 | lexer.more() 50 | } 51 | 52 | override fun hashCode(): Int { 53 | var hash = MurmurHash.initialize() 54 | hash = MurmurHash.update(hash, actionType.ordinal) 55 | return MurmurHash.finish(hash, 1) 56 | } 57 | 58 | override fun equals(obj: Any?): Boolean { 59 | return obj === this 60 | } 61 | 62 | override fun toString(): String { 63 | return "more" 64 | } 65 | 66 | companion object { 67 | /** 68 | * Provides a singleton instance of this parameterless lexer action. 69 | */ 70 | val INSTANCE = LexerMoreAction() 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPopModeAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `popMode` lexer action by calling [Lexer.popMode]. 14 | * 15 | * 16 | * The `popMode` command does not have any parameters, so this action is 17 | * implemented as a singleton instance exposed by [.INSTANCE]. 18 | * 19 | * @author Sam Harwell 20 | * @since 4.2 21 | */ 22 | class LexerPopModeAction 23 | /** 24 | * Constructs the singleton instance of the lexer `popMode` command. 25 | */ 26 | private constructor() : LexerAction { 27 | 28 | /** 29 | * {@inheritDoc} 30 | * @return This method returns [LexerActionType.POP_MODE]. 31 | */ 32 | override val actionType: LexerActionType 33 | get() = LexerActionType.POP_MODE 34 | 35 | /** 36 | * {@inheritDoc} 37 | * @return This method returns `false`. 38 | */ 39 | override val isPositionDependent: Boolean 40 | get() = false 41 | 42 | /** 43 | * {@inheritDoc} 44 | * 45 | * 46 | * This action is implemented by calling [Lexer.popMode]. 47 | */ 48 | override fun execute(lexer: Lexer) { 49 | lexer.popMode() 50 | } 51 | 52 | override fun hashCode(): Int { 53 | var hash = MurmurHash.initialize() 54 | hash = MurmurHash.update(hash, actionType.ordinal) 55 | return MurmurHash.finish(hash, 1) 56 | } 57 | 58 | override fun equals(obj: Any?): Boolean { 59 | return obj === this 60 | } 61 | 62 | override fun toString(): String { 63 | return "popMode" 64 | } 65 | 66 | companion object { 67 | /** 68 | * Provides a singleton instance of this parameterless lexer action. 69 | */ 70 | val INSTANCE = LexerPopModeAction() 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPushModeAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `pushMode` lexer action by calling 14 | * [Lexer.pushMode] with the assigned mode. 15 | * 16 | * @author Sam Harwell 17 | * @since 4.2 18 | */ 19 | class LexerPushModeAction 20 | /** 21 | * Constructs a new `pushMode` action with the specified mode value. 22 | * @param mode The mode value to pass to [Lexer.pushMode]. 23 | */ 24 | ( 25 | /** 26 | * Get the lexer mode this action should transition the lexer to. 27 | * 28 | * @return The lexer mode for this `pushMode` command. 29 | */ 30 | val mode: Int) : LexerAction { 31 | 32 | /** 33 | * {@inheritDoc} 34 | * @return This method returns [LexerActionType.PUSH_MODE]. 35 | */ 36 | override val actionType: LexerActionType 37 | get() = LexerActionType.PUSH_MODE 38 | 39 | /** 40 | * {@inheritDoc} 41 | * @return This method returns `false`. 42 | */ 43 | override val isPositionDependent: Boolean 44 | get() = false 45 | 46 | /** 47 | * {@inheritDoc} 48 | * 49 | * 50 | * This action is implemented by calling [Lexer.pushMode] with the 51 | * value provided by [.getMode]. 52 | */ 53 | override fun execute(lexer: Lexer) { 54 | lexer.pushMode(mode) 55 | } 56 | 57 | override fun hashCode(): Int { 58 | var hash = MurmurHash.initialize() 59 | hash = MurmurHash.update(hash, actionType.ordinal) 60 | hash = MurmurHash.update(hash, mode) 61 | return MurmurHash.finish(hash, 2) 62 | } 63 | 64 | override fun equals(obj: Any?): Boolean { 65 | if (obj === this) { 66 | return true 67 | } else if (obj !is LexerPushModeAction) { 68 | return false 69 | } 70 | 71 | return mode == obj.mode 72 | } 73 | 74 | override fun toString(): String { 75 | return "pushMode($mode)" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerSkipAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `skip` lexer action by calling [Lexer.skip]. 14 | * 15 | * 16 | * The `skip` command does not have any parameters, so this action is 17 | * implemented as a singleton instance exposed by [.INSTANCE]. 18 | * 19 | * @author Sam Harwell 20 | * @since 4.2 21 | */ 22 | class LexerSkipAction 23 | /** 24 | * Constructs the singleton instance of the lexer `skip` command. 25 | */ 26 | private constructor() : LexerAction { 27 | 28 | /** 29 | * {@inheritDoc} 30 | * @return This method returns [LexerActionType.SKIP]. 31 | */ 32 | override val actionType: LexerActionType 33 | get() = LexerActionType.SKIP 34 | 35 | /** 36 | * {@inheritDoc} 37 | * @return This method returns `false`. 38 | */ 39 | override val isPositionDependent: Boolean 40 | get() = false 41 | 42 | /** 43 | * {@inheritDoc} 44 | * 45 | * 46 | * This action is implemented by calling [Lexer.skip]. 47 | */ 48 | override fun execute(lexer: Lexer) { 49 | lexer.skip() 50 | } 51 | 52 | override fun hashCode(): Int { 53 | var hash = MurmurHash.initialize() 54 | hash = MurmurHash.update(hash, actionType.ordinal) 55 | return MurmurHash.finish(hash, 1) 56 | } 57 | 58 | override fun equals(obj: Any?): Boolean { 59 | return obj === this 60 | } 61 | 62 | override fun toString(): String { 63 | return "skip" 64 | } 65 | 66 | companion object { 67 | /** 68 | * Provides a singleton instance of this parameterless lexer action. 69 | */ 70 | val INSTANCE = LexerSkipAction() 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerTypeAction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Lexer 10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 11 | 12 | /** 13 | * Implements the `type` lexer action by calling [Lexer.setType] 14 | * with the assigned type. 15 | * 16 | * @author Sam Harwell 17 | * @since 4.2 18 | */ 19 | class LexerTypeAction 20 | /** 21 | * Constructs a new `type` action with the specified token type value. 22 | * @param type The type to assign to the token using [Lexer.setType]. 23 | */ 24 | ( 25 | /** 26 | * Gets the type to assign to a token created by the lexer. 27 | * @return The type to assign to a token created by the lexer. 28 | */ 29 | val type: Int) : LexerAction { 30 | 31 | /** 32 | * {@inheritDoc} 33 | * @return This method returns [LexerActionType.TYPE]. 34 | */ 35 | override val actionType: LexerActionType 36 | get() = LexerActionType.TYPE 37 | 38 | /** 39 | * {@inheritDoc} 40 | * @return This method returns `false`. 41 | */ 42 | override val isPositionDependent: Boolean 43 | get() = false 44 | 45 | /** 46 | * {@inheritDoc} 47 | * 48 | * 49 | * This action is implemented by calling [Lexer.setType] with the 50 | * value provided by [.getType]. 51 | */ 52 | override fun execute(lexer: Lexer) { 53 | lexer.type = type 54 | } 55 | 56 | override fun hashCode(): Int { 57 | var hash = MurmurHash.initialize() 58 | hash = MurmurHash.update(hash, actionType.ordinal) 59 | hash = MurmurHash.update(hash, type) 60 | return MurmurHash.finish(hash, 2) 61 | } 62 | 63 | override fun equals(obj: Any?): Boolean { 64 | if (obj === this) { 65 | return true 66 | } else if (obj !is LexerTypeAction) { 67 | return false 68 | } 69 | 70 | return type == obj.type 71 | } 72 | 73 | override fun toString(): String { 74 | return "type($type)" 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LookaheadEventInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.TokenStream 10 | 11 | /** 12 | * This class represents profiling event information for tracking the lookahead 13 | * depth required in order to make a prediction. 14 | * 15 | * @since 4.3 16 | */ 17 | class LookaheadEventInfo 18 | /** 19 | * Constructs a new instance of the [LookaheadEventInfo] class with 20 | * the specified detailed lookahead information. 21 | * 22 | * @param decision The decision number 23 | * @param configs The final configuration set containing the necessary 24 | * information to determine the result of a prediction, or `null` if 25 | * the final configuration set is not available 26 | * @param input The input token stream 27 | * @param startIndex The start index for the current prediction 28 | * @param stopIndex The index at which the prediction was finally made 29 | * @param fullCtx `true` if the current lookahead is part of an LL 30 | * prediction; otherwise, `false` if the current lookahead is part of 31 | * an SLL prediction 32 | */ 33 | (decision: Int, 34 | configs: ATNConfigSet, 35 | /** The alternative chosen by adaptivePredict(), not necessarily 36 | * the outermost alt shown for a rule; left-recursive rules have 37 | * user-level alts that differ from the rewritten rule with a (...) block 38 | * and a (..)* loop. 39 | */ 40 | var predictedAlt: Int, 41 | input: TokenStream, startIndex: Int, stopIndex: Int, 42 | fullCtx: Boolean) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) 43 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LoopEndState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** Mark the end of a * or + loop. */ 10 | class LoopEndState : ATNState() { 11 | var loopBackState: ATNState? = null 12 | 13 | override val stateType: Int 14 | get() = ATNState.LOOP_END 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/NotSetTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 10 | 11 | class NotSetTransition(target: ATNState, set: IntervalSet) : SetTransition(target, set) { 12 | 13 | override val serializationType: Int 14 | get() = Transition.NOT_SET 15 | 16 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 17 | return (symbol >= minVocabSymbol 18 | && symbol <= maxVocabSymbol 19 | && !super.matches(symbol, minVocabSymbol, maxVocabSymbol)) 20 | } 21 | 22 | override fun toString(): String { 23 | return '~' + super.toString() 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/OrderedATNConfigSet.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.misc.ObjectEqualityComparator 10 | 11 | /** 12 | * 13 | * @author Sam Harwell 14 | */ 15 | class OrderedATNConfigSet : ATNConfigSet() { 16 | init { 17 | this.configLookup = LexerConfigHashSet() 18 | } 19 | 20 | class LexerConfigHashSet : ATNConfigSet.AbstractConfigHashSet(ObjectEqualityComparator.INSTANCE) { 21 | override fun remove(element: ATNConfig): Boolean { 22 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 23 | } 24 | 25 | override fun containsAll(elements: Collection): Boolean { 26 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 27 | } 28 | 29 | override fun retainAll(elements: Collection): Boolean { 30 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PlusBlockStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** Start of `(A|B|...)+` loop. Technically a decision state, but 10 | * we don't use for code generation; somebody might need it, so I'm defining 11 | * it for completeness. In reality, the [PlusLoopbackState] node is the 12 | * real decision-making note for `A+`. 13 | */ 14 | class PlusBlockStartState : BlockStartState() { 15 | var loopBackState: PlusLoopbackState? = null 16 | 17 | override val stateType: Int 18 | get() = ATNState.PLUS_BLOCK_START 19 | } 20 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PlusLoopbackState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** Decision state for `A+` and `(A|B)+`. It has two transitions: 10 | * one to the loop back to start of the block and one to exit. 11 | */ 12 | class PlusLoopbackState : DecisionState() { 13 | 14 | override val stateType: Int 15 | get() = ATNState.PLUS_LOOP_BACK 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PrecedencePredicateTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** 10 | * 11 | * @author Sam Harwell 12 | */ 13 | class PrecedencePredicateTransition(target: ATNState, val precedence: Int) : AbstractPredicateTransition(target) { 14 | 15 | override val serializationType: Int 16 | get() = Transition.PRECEDENCE 17 | 18 | override val isEpsilon: Boolean 19 | get() = true 20 | 21 | val predicate: SemanticContext.PrecedencePredicate 22 | get() = SemanticContext.PrecedencePredicate(precedence) 23 | 24 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 25 | return false 26 | } 27 | 28 | override fun toString(): String { 29 | return precedence.toString() + " >= _p" 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredicateEvalInfo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.ParserRuleContext 10 | import org.antlr.v4.kotlinruntime.Recognizer 11 | import org.antlr.v4.kotlinruntime.RuleContext 12 | import org.antlr.v4.kotlinruntime.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 | * 21 | * @since 4.3 22 | */ 23 | class PredicateEvalInfo 24 | /** 25 | * Constructs a new instance of the [PredicateEvalInfo] class with the 26 | * specified detailed predicate evaluation information. 27 | * 28 | * @param decision The decision number 29 | * @param input The input token stream 30 | * @param startIndex The start index for the current prediction 31 | * @param stopIndex The index at which the predicate evaluation was 32 | * triggered. Note that the input stream may be reset to other positions for 33 | * the actual evaluation of individual predicates. 34 | * @param semctx The semantic context which was evaluated 35 | * @param evalResult The results of evaluating the semantic context 36 | * @param predictedAlt The alternative number for the decision which is 37 | * guarded by the semantic context `semctx`. See [.predictedAlt] 38 | * for more information. 39 | * @param fullCtx `true` if the semantic context was 40 | * evaluated during LL prediction; otherwise, `false` if the semantic 41 | * context was evaluated during SLL prediction 42 | * 43 | * @see ParserATNSimulator.evalSemanticContext 44 | * @see SemanticContext.eval 45 | */ 46 | (decision: Int, 47 | input: TokenStream, startIndex: Int, stopIndex: Int, 48 | /** 49 | * The semantic context which was evaluated. 50 | */ 51 | val semctx: SemanticContext, 52 | /** 53 | * The result of evaluating the semantic context [.semctx]. 54 | */ 55 | val evalResult: Boolean, 56 | /** 57 | * The alternative number for the decision which is guarded by the semantic 58 | * context [.semctx]. Note that other ATN 59 | * configurations may predict the same alternative which are guarded by 60 | * other semantic contexts and/or [SemanticContext.NONE]. 61 | */ 62 | val predictedAlt: Int, 63 | fullCtx: Boolean) : DecisionEventInfo(decision, ATNConfigSet(), input, startIndex, stopIndex, fullCtx) 64 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredicateTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** TODO: this is old comment: 10 | * A tree of semantic predicates from the grammar AST if accessLabel==SEMPRED. 11 | * In the ATN, labels will always be exactly one predicate, but the DFA 12 | * may have to combine a bunch of them as it collects predicates from 13 | * multiple ATN configurations into a single DFA state. 14 | */ 15 | class PredicateTransition(target: ATNState, val ruleIndex: Int, val predIndex: Int, val isCtxDependent: Boolean // e.g., $i ref in pred 16 | ) : AbstractPredicateTransition(target) { 17 | 18 | override val serializationType: Int 19 | get() = Transition.PREDICATE 20 | 21 | override val isEpsilon: Boolean 22 | get() = true 23 | 24 | val predicate: SemanticContext.Predicate 25 | get() = SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent) 26 | 27 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 28 | return false 29 | } 30 | 31 | override fun toString(): String { 32 | return "pred_$ruleIndex:$predIndex" 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredictionContextCache.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** Used to cache [PredictionContext] objects. Its used for the shared 10 | * context cash associated with contexts in DFA states. This cache 11 | * can be used for both lexers and parsers. 12 | */ 13 | class PredictionContextCache { 14 | protected val cache: MutableMap = HashMap() 15 | 16 | /** Add a context to the cache and return it. If the context already exists, 17 | * return that one instead and do not add a new context to the cache. 18 | * Protect shared cache from unsafe thread access. 19 | */ 20 | fun add(ctx: PredictionContext): PredictionContext { 21 | if (ctx === PredictionContext.EMPTY) return PredictionContext.EMPTY 22 | val existing = cache[ctx] 23 | if (existing != null) { 24 | // System.out.println(name+" reuses "+existing); 25 | return existing 26 | } 27 | cache.put(ctx, ctx) 28 | return ctx 29 | } 30 | 31 | operator fun get(ctx: PredictionContext): PredictionContext? { 32 | return cache[ctx] 33 | } 34 | 35 | fun size(): Int { 36 | return cache.size 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RangeTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 10 | 11 | class RangeTransition(target: ATNState, val from: Int, val to: Int) : Transition(target) { 12 | 13 | override val serializationType: Int 14 | get() = Transition.RANGE 15 | 16 | override fun accessLabel(): IntervalSet? { 17 | return IntervalSet.of(from, to) 18 | } 19 | 20 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 21 | return symbol >= from && symbol <= to 22 | } 23 | 24 | override fun toString(): String { 25 | TODO() 26 | // return StringBuilder("'") 27 | // .appendCodePoint(from) 28 | // .append("'..'") 29 | // .appendCodePoint(to) 30 | // .append("'") 31 | // .toString() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class RuleStartState : ATNState() { 10 | var stopState: RuleStopState? = null 11 | var isLeftRecursiveRule: Boolean = false 12 | 13 | override val stateType: Int 14 | get() = ATNState.RULE_START 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStopState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** The last node in the ATN for a rule, unless that rule is the start symbol. 10 | * In that case, there is one transition to EOF. Later, we might encode 11 | * references to all calls to this rule to compute FOLLOW sets for 12 | * error handling. 13 | */ 14 | class RuleStopState : ATNState() { 15 | 16 | override val stateType: Int 17 | get() = ATNState.RULE_STOP 18 | 19 | } 20 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** */ 10 | class RuleTransition(ruleStart: RuleStartState, 11 | /** Ptr to the rule definition object for this rule ref */ 12 | val ruleIndex: Int // no Rule object at runtime 13 | , 14 | val precedence: Int, 15 | /** What node to begin computations following ref to rule */ 16 | var followState: ATNState) : Transition(ruleStart) { 17 | 18 | override val serializationType: Int 19 | get() = Transition.RULE 20 | 21 | override val isEpsilon: Boolean 22 | get() = true 23 | 24 | 25 | @Deprecated("Use\n" + 26 | "\t {@link #RuleTransition(RuleStartState, int, int, ATNState)} instead.") 27 | constructor(ruleStart: RuleStartState, 28 | ruleIndex: Int, 29 | followState: ATNState) : this(ruleStart, ruleIndex, 0, followState) { 30 | } 31 | 32 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 33 | return false 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/SetTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.Token 10 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 11 | 12 | /** A transition containing a set of values. */ 13 | open class SetTransition// TODO (sam): should we really allow null here? 14 | (target: ATNState, set: IntervalSet?) : Transition(target) { 15 | val set: IntervalSet 16 | 17 | override val serializationType: Int 18 | get() = Transition.SET 19 | 20 | init { 21 | var set = set 22 | if (set == null) set = IntervalSet.of(Token.INVALID_TYPE) 23 | this.set = set 24 | } 25 | 26 | override fun accessLabel(): IntervalSet? { 27 | return set 28 | } 29 | 30 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 31 | return set.contains(symbol) 32 | } 33 | 34 | override fun toString(): String { 35 | return set.toString() 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/SingletonPredictionContext.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import com.strumenta.kotlinmultiplatform.assert 10 | 11 | open class SingletonPredictionContext internal constructor(val parent: PredictionContext?, val returnState: Int) : PredictionContext(if (parent != null) PredictionContext.calculateHashCode(parent, returnState) else PredictionContext.calculateEmptyHashCode()) { 12 | 13 | init { 14 | assert(returnState != ATNState.INVALID_STATE_NUMBER) 15 | } 16 | 17 | override fun size(): Int { 18 | return 1 19 | } 20 | 21 | override fun getParent(index: Int): PredictionContext? { 22 | assert(index == 0) 23 | return parent 24 | } 25 | 26 | override fun getReturnState(index: Int): Int { 27 | assert(index == 0) 28 | return returnState 29 | } 30 | 31 | override fun equals(o: Any?): Boolean { 32 | if (this === o) { 33 | return true 34 | } else if (o !is SingletonPredictionContext) { 35 | return false 36 | } 37 | 38 | if (this.hashCode() != o.hashCode()) { 39 | return false // can't be same if hash is different 40 | } 41 | 42 | val s = o as SingletonPredictionContext? 43 | return returnState == s!!.returnState && parent != null && parent == s.parent 44 | } 45 | 46 | override fun toString(): String { 47 | val up = if (parent != null) parent!!.toString() else "" 48 | return if (up.length == 0) { 49 | if (returnState == PredictionContext.EMPTY_RETURN_STATE) { 50 | "$" 51 | } else returnState.toString() 52 | } else returnState.toString() + " " + up 53 | } 54 | 55 | companion object { 56 | 57 | fun create(parent: PredictionContext?, returnState: Int): SingletonPredictionContext { 58 | return if (returnState == PredictionContext.EMPTY_RETURN_STATE && parent == null) { 59 | // someone can pass in the bits of an array ctx that mean $ 60 | PredictionContext.EMPTY 61 | } else SingletonPredictionContext(parent, returnState) 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarBlockStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** The block that begins a closure loop. */ 10 | class StarBlockStartState : BlockStartState() { 11 | 12 | override val stateType: Int 13 | get() = ATNState.STAR_BLOCK_START 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopEntryState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | import org.antlr.v4.kotlinruntime.dfa.DFA 10 | 11 | class StarLoopEntryState : DecisionState() { 12 | var loopBackState: StarLoopbackState? = null 13 | 14 | /** 15 | * Indicates whether this state can benefit from a precedence DFA during SLL 16 | * decision making. 17 | * 18 | * 19 | * This is a computed property that is calculated during ATN deserialization 20 | * and stored for use in [ParserATNSimulator] and 21 | * [ParserInterpreter]. 22 | * 23 | * @see DFA.isPrecedenceDfa 24 | */ 25 | var isPrecedenceDecision: Boolean = false 26 | 27 | override val stateType: Int 28 | get() = ATNState.STAR_LOOP_ENTRY 29 | } 30 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopbackState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class StarLoopbackState : ATNState() { 10 | val loopEntryState: StarLoopEntryState 11 | get() = transition(0).target as StarLoopEntryState 12 | 13 | override val stateType: Int 14 | get() = ATNState.STAR_LOOP_BACK 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/TokensStartState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | /** The Tokens rule start state linking to each lexer rule start state */ 10 | class TokensStartState : DecisionState() { 11 | 12 | override val stateType: Int 13 | get() = ATNState.TOKEN_START 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/WildcardTransition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.atn 8 | 9 | class WildcardTransition(target: ATNState) : Transition(target) { 10 | 11 | override val serializationType: Int 12 | get() = Transition.WILDCARD 13 | 14 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean { 15 | return symbol >= minVocabSymbol && symbol <= maxVocabSymbol 16 | } 17 | 18 | override fun toString(): String { 19 | return "." 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/dfa/DFASerializer.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.dfa 8 | 9 | import com.strumenta.kotlinmultiplatform.Arrays 10 | import org.antlr.v4.kotlinruntime.Vocabulary 11 | import org.antlr.v4.kotlinruntime.VocabularyImpl 12 | 13 | /** A DFA walker that knows how to dump them to serialized strings. */ 14 | open class DFASerializer { 15 | 16 | private val dfa: DFA 17 | 18 | private val vocabulary: Vocabulary 19 | 20 | 21 | @Deprecated("Use {@link #DFASerializer(DFA, Vocabulary)} instead.") 22 | constructor(dfa: DFA, tokenNames: Array) : this(dfa, VocabularyImpl.fromTokenNames(tokenNames as Array)) { 23 | } 24 | 25 | constructor(dfa: DFA, vocabulary: Vocabulary) { 26 | this.dfa = dfa 27 | this.vocabulary = vocabulary 28 | } 29 | 30 | override fun toString(): String { 31 | if (dfa.s0 == null) return "null" 32 | val buf = StringBuilder() 33 | val states = dfa.getStates() 34 | for (s in states) { 35 | var n = 0 36 | if (s.edges != null) n = s.edges!!.size 37 | for (i in 0 until n) { 38 | val t = s.edges!![i] 39 | if (t != null && t!!.stateNumber != Int.MAX_VALUE) { 40 | buf.append(getStateString(s)) 41 | val label = getEdgeLabel(i) 42 | buf.append("-").append(label).append("->").append(getStateString(t)).append('\n') 43 | } 44 | } 45 | } 46 | 47 | val output = buf.toString() 48 | return if (output.length == 0) "null" else output 49 | //return Utils.sortLinesInString(output); 50 | } 51 | 52 | protected open fun getEdgeLabel(i: Int): String { 53 | return vocabulary.getDisplayName(i - 1) 54 | } 55 | 56 | 57 | protected fun getStateString(s: DFAState): String { 58 | val n = s.stateNumber 59 | val baseStateStr = (if (s.isAcceptState) ":" else "") + "s" + n + if (s.requiresFullContext) "^" else "" 60 | return if (s.isAcceptState) { 61 | if (s.predicates != null) { 62 | baseStateStr + "=>" + Arrays.toString(s.predicates!!) 63 | } else { 64 | baseStateStr + "=>" + s.prediction 65 | } 66 | } else { 67 | baseStateStr 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/dfa/LexerDFASerializer.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.dfa 8 | 9 | import org.antlr.v4.kotlinruntime.VocabularyImpl 10 | 11 | class LexerDFASerializer(dfa: DFA) : DFASerializer(dfa, VocabularyImpl.EMPTY_VOCABULARY) { 12 | 13 | protected override fun getEdgeLabel(i: Int): String { 14 | TODO() 15 | // return StringBuilder("'") 16 | // .appendCodePoint(i) 17 | // .append("'") 18 | // .toString() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/AbstractEqualityComparator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime.misc 7 | 8 | /** 9 | * This abstract base class is provided so performance-critical applications can 10 | * use virtual- instead of interface-dispatch when calling comparator methods. 11 | * 12 | * @author Sam Harwell 13 | */ 14 | abstract class AbstractEqualityComparator : EqualityComparator 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/DoubleKeyMap.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | /** Sometimes we need to map a key to a value but key is two pieces of data. 10 | * This nested hash table saves creating a single key each time we access 11 | * map; avoids mem creation. 12 | */ 13 | class DoubleKeyMap { 14 | internal var data: MutableMap> = LinkedHashMap() 15 | 16 | fun put(k1: Key1, k2: Key2, v: Value): Value? { 17 | var data2: MutableMap? = data[k1] 18 | var prev: Value? = null 19 | if (data2 == null) { 20 | data2 = LinkedHashMap() 21 | data.put(k1, data2) 22 | } else { 23 | prev = data2[k2] 24 | } 25 | data2.put(k2, v) 26 | return prev 27 | } 28 | 29 | operator fun get(k1: Key1, k2: Key2): Value? { 30 | val data2 = data[k1] ?: return null 31 | return data2[k2] 32 | } 33 | 34 | operator fun get(k1: Key1): Map { 35 | return data[k1]!! 36 | } 37 | 38 | /** Get all values associated with primary key */ 39 | fun values(k1: Key1): Collection? { 40 | val data2 = data[k1] ?: return null 41 | return data2.values 42 | } 43 | 44 | /** get all primary keys */ 45 | fun keySet(): Set { 46 | return data.keys 47 | } 48 | 49 | /** get all secondary keys associated with a primary key */ 50 | fun keySet(k1: Key1): Set? { 51 | val data2 = data[k1] ?: return null 52 | return data2.keys 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/EqualityComparator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime.misc 7 | 8 | /** 9 | * This interface provides an abstract concept of object equality independent of 10 | * [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 | interface EqualityComparator { 17 | 18 | /** 19 | * This method returns a hash code for the specified object. 20 | * 21 | * @param obj The object. 22 | * @return The hash code for `obj`. 23 | */ 24 | fun hashCode(obj: T): Int 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 | * @return `true` if `a` equals `b`, otherwise `false`. 32 | */ 33 | fun equals(a: T?, b: T?): Boolean 34 | 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/IntegerStack.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime.misc 7 | 8 | /** 9 | * 10 | * @author Sam Harwell 11 | */ 12 | class IntegerStack : IntegerList { 13 | 14 | constructor() {} 15 | 16 | constructor(capacity: Int) : super(capacity) {} 17 | 18 | constructor(list: IntegerStack) : super(list) {} 19 | 20 | fun push(value: Int) { 21 | add(value) 22 | } 23 | 24 | fun pop(): Int { 25 | return removeAt(size() - 1) 26 | } 27 | 28 | fun peek(): Int { 29 | return get(size() - 1) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/MultiMap.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | class MultiMap : MutableMap> by mutableMapOf() { 10 | 11 | val pairs: List> 12 | get() { 13 | val pairs = ArrayList>() 14 | for (key in keys) { 15 | for (value in get(key)!!) { 16 | pairs.add(Pair(key, value)) 17 | } 18 | } 19 | return pairs 20 | } 21 | 22 | fun map(key: K, value: V) { 23 | var elementsForKey: MutableList? = get(key) 24 | if (elementsForKey == null) { 25 | elementsForKey = ArrayList() 26 | put(key, elementsForKey) 27 | } 28 | elementsForKey.add(value) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/NotNull.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime.misc 7 | 8 | @Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.LOCAL_VARIABLE) 9 | @Deprecated("THIS IS HERE FOR BACKWARD COMPATIBILITY WITH 4.5 ONLY. It will\n" + 10 | " disappear in 4.6+") 11 | annotation class NotNull 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/ObjectEqualityComparator.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | package org.antlr.v4.kotlinruntime.misc 7 | 8 | /** 9 | * This default implementation of [EqualityComparator] uses object equality 10 | * for comparisons by calling [Object.hashCode] and [Object.equals]. 11 | * 12 | * @author Sam Harwell 13 | */ 14 | class ObjectEqualityComparator : AbstractEqualityComparator() { 15 | override fun hashCode(obj: T): Int { 16 | return obj?.hashCode() ?: 0 17 | } 18 | 19 | /** 20 | * {@inheritDoc} 21 | * 22 | * 23 | * This implementation relies on object equality. If both objects are 24 | * `null`, this method returns `true`. Otherwise if only 25 | * `a` is `null`, this method returns `false`. Otherwise, 26 | * this method returns the result of 27 | * `a.`[equals][Object.equals]`(b)`. 28 | */ 29 | override fun equals(a: T?, b: T?): Boolean { 30 | return if (a == null) { 31 | b == null 32 | } else a == b 33 | } 34 | 35 | 36 | 37 | companion object { 38 | val INSTANCE = ObjectEqualityComparator() 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/OrderedHashSet.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | /** A HashMap that remembers the order that the elements were added. 10 | * You can alter the ith element with set(i,value) too :) Unique list. 11 | * I need the replace/set-element-i functionality so I'm subclassing 12 | * LinkedHashSet. 13 | */ 14 | class OrderedHashSet : Set by mutableSetOf() { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Pair.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | class Pair(val a: A?, val b: B?) { 10 | 11 | override fun equals(obj: Any?): Boolean { 12 | if (obj === this) { 13 | return true 14 | } else if (obj !is Pair<*, *>) { 15 | return false 16 | } 17 | 18 | val other = obj as Pair<*, *>? 19 | return ObjectEqualityComparator().equals(a, other!!.a) && ObjectEqualityComparator().equals(b, other.b) 20 | } 21 | 22 | override fun hashCode(): Int { 23 | var hash = MurmurHash.initialize() 24 | hash = MurmurHash.update(hash, a) 25 | hash = MurmurHash.update(hash, b) 26 | return MurmurHash.finish(hash, 2) 27 | } 28 | 29 | override fun toString(): String { 30 | return "($a, $b)" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/ParseCancellationException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | import org.antlr.v4.kotlinruntime.BailErrorStrategy 10 | import org.antlr.v4.kotlinruntime.RecognitionException 11 | 12 | /** 13 | * This exception is thrown to cancel a parsing operation. This exception does 14 | * not extend [RecognitionException], allowing it to bypass the standard 15 | * error recovery mechanisms. [BailErrorStrategy] throws this exception in 16 | * response to a parse error. 17 | * 18 | * @author Sam Harwell 19 | */ 20 | class ParseCancellationException : RuntimeException { 21 | 22 | constructor() {} 23 | 24 | constructor(message: String) {} 25 | 26 | constructor(cause: Throwable) { 27 | TODO() 28 | //initCause(cause) 29 | } 30 | 31 | constructor(message: String, cause: Throwable) { 32 | TODO() 33 | //initCause(cause) 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Predicate.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | interface Predicate { 10 | fun test(t: T): Boolean 11 | } 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Triple.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.misc 8 | 9 | class Triple(val a: A, val b: B, val c: C) { 10 | 11 | override fun equals(obj: Any?): Boolean { 12 | if (obj === this) { 13 | return true 14 | } else if (obj !is Triple<*, *, *>) { 15 | return false 16 | } 17 | 18 | val other = obj as Triple<*, *, *>? 19 | return (ObjectEqualityComparator().equals(a, other!!.a) 20 | && ObjectEqualityComparator().equals(b, other.b) 21 | && ObjectEqualityComparator().equals(c, other.c)) 22 | } 23 | 24 | override fun hashCode(): Int { 25 | var hash = MurmurHash.initialize() 26 | hash = MurmurHash.update(hash, a) 27 | hash = MurmurHash.update(hash, b) 28 | hash = MurmurHash.update(hash, c) 29 | return MurmurHash.finish(hash, 3) 30 | } 31 | 32 | override fun toString(): String { 33 | return "($a, $b, $c)" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNode.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | interface ErrorNode : TerminalNode 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNodeImpl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.Token 10 | 11 | /** Represents a token that was consumed during resynchronization 12 | * rather than during a valid match operation. For example, 13 | * we will create this kind of a node during single token insertion 14 | * and deletion as well as during "consume until error recovery set" 15 | * upon no viable alternative exceptions. 16 | */ 17 | class ErrorNodeImpl(token: Token) : TerminalNodeImpl(token), ErrorNode { 18 | 19 | override fun accept(visitor: ParseTreeVisitor): T?{ 20 | return visitor.visitErrorNode(this) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.Parser 10 | import org.antlr.v4.kotlinruntime.RuleContext 11 | import org.antlr.v4.kotlinruntime.Token 12 | 13 | /** An interface to access the tree of [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 | * 19 | * The payload is either a [Token] or a [RuleContext] object. 20 | */ 21 | interface ParseTree : SyntaxTree { 22 | // the following methods narrow the return type; they are not additional methods 23 | //override var parent: ParseTree? 24 | 25 | //private var parent : ParseTree? = null 26 | 27 | fun assignParent(value: ParseTree?) 28 | // this.parent = value 29 | //} 30 | 31 | override fun readParent() : ParseTree? 32 | 33 | /** Return the combined text of all leaf nodes. Does not get any 34 | * off-channel tokens (if any) so won't return whitespace and 35 | * comments if they are sent to parser on hidden channel. 36 | */ 37 | val text: String 38 | 39 | override fun getChild(i: Int): ParseTree? 40 | 41 | 42 | /** Set the parent for this node. 43 | * 44 | * This is not backward compatible as it changes 45 | * the interface but no one was able to create custom 46 | * nodes anyway so I'm adding as it improves internal 47 | * code quality. 48 | * 49 | * One could argue for a restructuring of 50 | * the class/interface hierarchy so that 51 | * setParent, addChild are moved up to Tree 52 | * but that's a major change. So I'll do the 53 | * minimal change, which is to add this method. 54 | * 55 | * @since 4.7 56 | */ 57 | //fun setParent(parent: RuleContext) 58 | 59 | /** The [ParseTreeVisitor] needs a double dispatch method. */ 60 | fun accept(visitor: ParseTreeVisitor): T? 61 | 62 | /** Specialize toStringTree so that it can print out more information 63 | * based upon the parser. 64 | */ 65 | fun toStringTree(parser: Parser): String 66 | } 67 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeListener.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.ParserRuleContext 10 | 11 | /** This interface describes the minimal core of methods triggered 12 | * by [ParseTreeWalker]. E.g., 13 | * 14 | * ParseTreeWalker walker = new ParseTreeWalker(); 15 | * walker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener 16 | * 17 | * If you want to trigger events in multiple listeners during a single 18 | * tree walk, you can use the ParseTreeDispatcher object available at 19 | * 20 | * https://github.com/antlr/antlr4/issues/841 21 | */ 22 | interface ParseTreeListener { 23 | fun visitTerminal(node: TerminalNode) 24 | fun visitErrorNode(node: ErrorNode) 25 | fun enterEveryRule(ctx: ParserRuleContext) 26 | fun exitEveryRule(ctx: ParserRuleContext) 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeProperty.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import com.strumenta.kotlinmultiplatform.IdentityHashMap 10 | 11 | /** 12 | * Associate a property with a parse tree node. Useful with parse tree listeners 13 | * that need to associate values with particular tree nodes, kind of like 14 | * specifying a return value for the listener event method that visited a 15 | * particular node. Example: 16 | * 17 | *
18 |  * ParseTreeProperty<Integer> values = new ParseTreeProperty<Integer>();
19 |  * values.put(tree, 36);
20 |  * int x = values.get(tree);
21 |  * values.removeFrom(tree);
22 | 
* 23 | * 24 | * You would make one decl (values here) in the listener and use lots of times 25 | * in your event methods. 26 | */ 27 | class ParseTreeProperty { 28 | protected var annotations: MutableMap = IdentityHashMap() 29 | 30 | operator fun get(node: ParseTree): V { 31 | return annotations[node]!! 32 | } 33 | 34 | fun put(node: ParseTree, value: V) { 35 | annotations.put(node, value) 36 | } 37 | 38 | fun removeFrom(node: ParseTree): V { 39 | return annotations.remove(node)!! 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeVisitor.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | /** 10 | * This interface defines the basic notion of a parse tree visitor. Generated 11 | * visitors implement this interface and the `XVisitor` interface for 12 | * grammar `X`. 13 | * 14 | * @param The return type of the visit operation. Use [Void] for 15 | * operations with no return type. 16 | */ 17 | interface ParseTreeVisitor { 18 | 19 | /** 20 | * Visit a parse tree, and return a user-defined result of the operation. 21 | * 22 | * @param tree The [ParseTree] to visit. 23 | * @return The result of visiting the parse tree. 24 | */ 25 | fun visit(tree: ParseTree): T? 26 | 27 | /** 28 | * Visit the children of a node, and return a user-defined result of the 29 | * operation. 30 | * 31 | * @param node The [RuleNode] whose children should be visited. 32 | * @return The result of visiting the children of the node. 33 | */ 34 | fun visitChildren(node: RuleNode): T? 35 | 36 | /** 37 | * Visit a terminal node, and return a user-defined result of the operation. 38 | * 39 | * @param node The [TerminalNode] to visit. 40 | * @return The result of visiting the node. 41 | */ 42 | fun visitTerminal(node: TerminalNode): T? 43 | 44 | /** 45 | * Visit an error node, and return a user-defined result of the operation. 46 | * 47 | * @param node The [ErrorNode] to visit. 48 | * @return The result of visiting the node. 49 | */ 50 | fun visitErrorNode(node: ErrorNode): T? 51 | 52 | } 53 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeWalker.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.ParserRuleContext 10 | import org.antlr.v4.kotlinruntime.RuleContext 11 | 12 | open class ParseTreeWalker { 13 | 14 | open fun walk(listener: ParseTreeListener, t: ParseTree) { 15 | if (t is ErrorNode) { 16 | listener.visitErrorNode(t as ErrorNode) 17 | return 18 | } else if (t is TerminalNode) { 19 | listener.visitTerminal(t as TerminalNode) 20 | return 21 | } 22 | val r = t as RuleNode 23 | enterRule(listener, r) 24 | val n = r.childCount 25 | for (i in 0 until n) { 26 | walk(listener, r.getChild(i)!!) 27 | } 28 | exitRule(listener, r) 29 | } 30 | 31 | /** 32 | * The discovery of a rule node, involves sending two events: the generic 33 | * [ParseTreeListener.enterEveryRule] and a 34 | * [RuleContext]-specific event. First we trigger the generic and then 35 | * the rule specific. We to them in reverse order upon finishing the node. 36 | */ 37 | protected fun enterRule(listener: ParseTreeListener, r: RuleNode) { 38 | val ctx = r.ruleContext as ParserRuleContext 39 | listener.enterEveryRule(ctx) 40 | ctx.enterRule(listener) 41 | } 42 | 43 | protected fun exitRule(listener: ParseTreeListener, r: RuleNode) { 44 | val ctx = r.ruleContext as ParserRuleContext 45 | ctx.exitRule(listener) 46 | listener.exitEveryRule(ctx) 47 | } 48 | 49 | companion object { 50 | val DEFAULT = ParseTreeWalker() 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/RuleNode.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.RuleContext 10 | 11 | interface RuleNode : ParseTree { 12 | val ruleContext: RuleContext 13 | } 14 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/SyntaxTree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.TokenStream 10 | import org.antlr.v4.kotlinruntime.misc.Interval 11 | 12 | /** A tree that knows about an interval in a token stream 13 | * is some kind of syntax tree. Subinterfaces distinguish 14 | * between parse trees and other kinds of syntax trees we might want to create. 15 | */ 16 | interface SyntaxTree : Tree { 17 | /** 18 | * Return an [Interval] indicating the index in the 19 | * [TokenStream] of the first and last token associated with this 20 | * subtree. If this node is a leaf, then the interval represents a single 21 | * token and has interval i..i for token index i. 22 | * 23 | * 24 | * An interval of i..i-1 indicates an empty interval at position 25 | * i in the input stream, where 0 <= i <= the size of the input 26 | * token stream. Currently, the code base can only have i=0..n-1 but 27 | * in concept one could have an empty interval after EOF. 28 | * 29 | * 30 | * If source interval is unknown, this returns [Interval.INVALID]. 31 | * 32 | * 33 | * As a weird special case, the source interval for rules matched after 34 | * EOF is unspecified. 35 | */ 36 | val sourceInterval: Interval 37 | } 38 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/TerminalNode.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.Token 10 | 11 | interface TerminalNode : ParseTree { 12 | val symbol: Token? 13 | } 14 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/TerminalNodeImpl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.Parser 10 | import org.antlr.v4.kotlinruntime.RuleContext 11 | import org.antlr.v4.kotlinruntime.Token 12 | import org.antlr.v4.kotlinruntime.misc.Interval 13 | 14 | open class TerminalNodeImpl(override var symbol: Token?) : TerminalNode { 15 | 16 | private var parent : ParseTree? = null 17 | 18 | override fun assignParent(value: ParseTree?) { 19 | this.parent = value 20 | } 21 | 22 | override fun readParent(): ParseTree? { 23 | return this.parent 24 | } 25 | //override var parent: ParseTree? = null 26 | 27 | override val sourceInterval: Interval 28 | get() { 29 | if (symbol == null) return Interval.INVALID 30 | 31 | val tokenIndex = symbol!!.tokenIndex 32 | return Interval(tokenIndex, tokenIndex) 33 | } 34 | 35 | override val childCount: Int 36 | get() = 0 37 | 38 | override val text: String 39 | get() = symbol!!.text!! 40 | 41 | override fun getChild(i: Int): ParseTree? { 42 | return null 43 | } 44 | 45 | // override fun setParent(parent: RuleContext) { 46 | // this.parent = parent 47 | // } 48 | 49 | override val payload: Token? 50 | get() = symbol 51 | 52 | override fun accept(visitor: ParseTreeVisitor): T? { 53 | return visitor.visitTerminal(this) 54 | } 55 | 56 | override fun toStringTree(parser: Parser): String { 57 | return toString() 58 | } 59 | 60 | override fun toString(): String { 61 | return if (symbol!!.type === Token.EOF) "" else symbol!!.text!! 62 | } 63 | 64 | override fun toStringTree(): String { 65 | return toString() 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/Tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree 8 | 9 | import org.antlr.v4.kotlinruntime.RuleContext 10 | import org.antlr.v4.kotlinruntime.Token 11 | 12 | /** The basic notion of a tree has a parent, a payload, and a list of children. 13 | * It is the most abstract interface for all the trees used by ANTLR. 14 | */ 15 | interface Tree { 16 | /** The parent of this node. If the return value is null, then this 17 | * node is the root of the tree. 18 | */ 19 | //var parent: Tree? 20 | 21 | //private var parent : Tree? 22 | 23 | // public fun assignParent(value: ParseTree?) { 24 | // this.parent = value 25 | // } 26 | 27 | fun readParent() : Tree? 28 | /** 29 | * This method returns whatever object represents the data at this note. For 30 | * example, for parse trees, the payload can be a [Token] representing 31 | * a leaf node or a [RuleContext] object representing a rule 32 | * invocation. For abstract syntax trees (ASTs), this is a [Token] 33 | * object. 34 | */ 35 | val payload: Any? 36 | 37 | /** How many children are there? If there is none, then this 38 | * node represents a leaf node. 39 | */ 40 | val childCount: Int 41 | 42 | /** If there are children, get the `i`th value indexed from 0. */ 43 | fun getChild(i: Int): Tree? 44 | 45 | /** Print out a whole tree, not just a node, in LISP format 46 | * `(root child1 .. childN)`. Print just a node if this is a leaf. 47 | */ 48 | fun toStringTree(): String 49 | } 50 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/Chunk.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.pattern 8 | 9 | /** 10 | * A chunk is either a token tag, a rule tag, or a span of literal text within a 11 | * tree pattern. 12 | * 13 | * 14 | * The method [ParseTreePatternMatcher.split] returns a list of 15 | * chunks in preparation for creating a token stream by 16 | * [ParseTreePatternMatcher.tokenize]. From there, we get a parse 17 | * tree from with [ParseTreePatternMatcher.compile]. These 18 | * chunks are converted to [RuleTagToken], [TokenTagToken], or the 19 | * regular tokens of the text surrounding the tags. 20 | */ 21 | internal abstract class Chunk 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/TextChunk.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.pattern 8 | 9 | /** 10 | * Represents a span of raw text (concrete syntax) between tags in a tree 11 | * pattern string. 12 | */ 13 | internal class TextChunk 14 | /** 15 | * Constructs a new instance of [TextChunk] with the specified text. 16 | * 17 | * @param text The text of this chunk. 18 | * @exception IllegalArgumentException if `text` is `null`. 19 | */ 20 | ( 21 | /** 22 | * This is the backing field for [.getText]. 23 | */ 24 | 25 | /** 26 | * Gets the raw text of this chunk. 27 | * 28 | * @return The text of the chunk. 29 | */ 30 | 31 | val text: String?) : Chunk() { 32 | 33 | init { 34 | if (text == null) { 35 | throw IllegalArgumentException("text cannot be null") 36 | } 37 | } 38 | 39 | /** 40 | * {@inheritDoc} 41 | * 42 | * 43 | * The implementation for [TextChunk] returns the result of 44 | * [.getText] in single quotes. 45 | */ 46 | override fun toString(): String { 47 | return "'$text'" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/TokenTagToken.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.pattern 8 | 9 | import org.antlr.v4.kotlinruntime.CommonToken 10 | import org.antlr.v4.kotlinruntime.Token 11 | 12 | /** 13 | * A [Token] object representing a token of a particular type; e.g., 14 | * ``. These tokens are created for [TagChunk] chunks where the 15 | * tag corresponds to a lexer rule or token type. 16 | */ 17 | class TokenTagToken 18 | /** 19 | * Constructs a new instance of [TokenTagToken] with the specified 20 | * token name, type, and accessLabel. 21 | * 22 | * @param tokenName The token name. 23 | * @param type The token type. 24 | * @param label The accessLabel associated with the token tag, or `null` if 25 | * the token tag is unlabeled. 26 | */ 27 | constructor( 28 | /** 29 | * This is the backing field for [.getTokenName]. 30 | */ 31 | 32 | /** 33 | * Gets the token name. 34 | * @return The token name. 35 | */ 36 | 37 | val tokenName: String, type: Int, 38 | /** 39 | * This is the backing field for [.getLabel]. 40 | */ 41 | 42 | /** 43 | * Gets the accessLabel associated with the rule tag. 44 | * 45 | * @return The name of the accessLabel associated with the rule tag, or 46 | * `null` if this is an unlabeled rule tag. 47 | */ 48 | 49 | val label: String? = null) : CommonToken(type) { 50 | 51 | /** 52 | * {@inheritDoc} 53 | * 54 | * 55 | * The implementation for [TokenTagToken] returns the token tag 56 | * formatted with `<` and `>` delimiters. 57 | */ 58 | override var text: String? = null 59 | get() = if (label != null) { 60 | "<$label:$tokenName>" 61 | } else "<$tokenName>" 62 | 63 | /** 64 | * {@inheritDoc} 65 | * 66 | * 67 | * The implementation for [TokenTagToken] returns a string of the form 68 | * `tokenName:type`. 69 | */ 70 | override fun toString(): String { 71 | return tokenName + ":" + type 72 | } 73 | } 74 | /** 75 | * Constructs a new instance of [TokenTagToken] for an unlabeled tag 76 | * with the specified token name and type. 77 | * 78 | * @param tokenName The token name. 79 | * @param type The token type. 80 | */ 81 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathElement.kt: -------------------------------------------------------------------------------- 1 | ///* 2 | // * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | // * Use of this file is governed by the BSD 3-clause license that 4 | // * can be found in the LICENSE.txt file in the project root. 5 | // */ 6 | // 7 | //package org.antlr.v4.kotlinruntime.tree.xpath 8 | // 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | // 11 | //abstract class XPathElement 12 | ///** Construct element like `/ID` or `ID` or `/*` etc... 13 | // * op is null if just node 14 | //*/ 15 | //(protected var nodeName:String) { 16 | //var invert:Boolean = false 17 | // 18 | ///** 19 | // * Given tree rooted at `t` return all nodes matched by this path 20 | // * element. 21 | //*/ 22 | //abstract fun evaluate(t:ParseTree):Collection 23 | // 24 | //public override fun toString():String { 25 | //val inv = if (invert) "!" else "" 26 | //return javaClass.getSimpleName() + "[" + inv + nodeName + "]" 27 | //} 28 | //} 29 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathLexerErrorListener.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | 9 | //import org.antlr.v4.runtime.BaseErrorListener 10 | //import org.antlr.v4.runtime.RecognitionException 11 | //import org.antlr.v4.runtime.Recognizer 12 | // 13 | //class XPathLexerErrorListener : BaseErrorListener() { 14 | // fun syntaxError(recognizer: Recognizer<*, *>, offendingSymbol: Any, 15 | // line: Int, charPositionInLine: Int, msg: String, 16 | // e: RecognitionException) { 17 | // } 18 | //} 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathRuleAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | // 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | //import org.antlr.v4.runtime.tree.Trees 11 | // 12 | ///** 13 | // * Either `ID` at start of path or `...//ID` in middle of path. 14 | // */ 15 | //class XPathRuleAnywhereElement(ruleName: String, protected var ruleIndex: Int) : XPathElement(ruleName) { 16 | // 17 | // override fun evaluate(t: ParseTree): Collection { 18 | // return Trees.findAllRuleNodes(t, ruleIndex) 19 | // } 20 | //} 21 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathRuleElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | 9 | //import org.antlr.v4.runtime.ParserRuleContext 10 | //import org.antlr.v4.runtime.tree.ParseTree 11 | //import org.antlr.v4.runtime.tree.Tree 12 | //import org.antlr.v4.runtime.tree.Trees 13 | // 14 | //import java.util.ArrayList 15 | // 16 | //class XPathRuleElement(ruleName: String, protected var ruleIndex: Int) : XPathElement(ruleName) { 17 | // 18 | // override fun evaluate(t: ParseTree): Collection { 19 | // // return all children of t that match nodeName 20 | // val nodes = ArrayList() 21 | // for (c in Trees.getChildren(t)) { 22 | // if (c is ParserRuleContext) { 23 | // val ctx = c as ParserRuleContext 24 | // if (ctx.getRuleIndex() === ruleIndex && !invert || ctx.getRuleIndex() !== ruleIndex && invert) { 25 | // nodes.add(ctx) 26 | // } 27 | // } 28 | // } 29 | // return nodes 30 | // } 31 | //} 32 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathTokenAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | //import org.antlr.v4.runtime.tree.Trees 11 | // 12 | //class XPathTokenAnywhereElement(tokenName: String, protected var tokenType: Int) : XPathElement(tokenName) { 13 | // 14 | // override fun evaluate(t: ParseTree): Collection { 15 | // return Trees.findAllTokenNodes(t, tokenType) 16 | // } 17 | //} 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathTokenElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | // 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | //import org.antlr.v4.runtime.tree.TerminalNode 11 | //import org.antlr.v4.runtime.tree.Tree 12 | //import org.antlr.v4.runtime.tree.Trees 13 | // 14 | //import java.util.ArrayList 15 | // 16 | //class XPathTokenElement(tokenName: String, protected var tokenType: Int) : XPathElement(tokenName) { 17 | // 18 | // override fun evaluate(t: ParseTree): Collection { 19 | // // return all children of t that match nodeName 20 | // val nodes = ArrayList() 21 | // for (c in Trees.getChildren(t)) { 22 | // if (c is TerminalNode) { 23 | // val tnode = c as TerminalNode 24 | // if (tnode.getSymbol().getType() === tokenType && !invert || tnode.getSymbol().getType() !== tokenType && invert) { 25 | // nodes.add(tnode) 26 | // } 27 | // } 28 | // } 29 | // return nodes 30 | // } 31 | //} 32 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathWildcardAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | // 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | //import org.antlr.v4.runtime.tree.Trees 11 | // 12 | //import java.util.ArrayList 13 | // 14 | //class XPathWildcardAnywhereElement : XPathElement(XPath.WILDCARD) { 15 | // 16 | // override fun evaluate(t: ParseTree): Collection { 17 | // return if (invert) ArrayList() else Trees.getDescendants(t) // !* is weird but valid (empty) 18 | // } 19 | //} 20 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathWildcardElement.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 3 | * Use of this file is governed by the BSD 3-clause license that 4 | * can be found in the LICENSE.txt file in the project root. 5 | */ 6 | 7 | package org.antlr.v4.kotlinruntime.tree.xpath 8 | 9 | //import org.antlr.v4.runtime.tree.ParseTree 10 | //import org.antlr.v4.runtime.tree.Tree 11 | //import org.antlr.v4.runtime.tree.Trees 12 | // 13 | //import java.util.ArrayList 14 | // 15 | //class XPathWildcardElement : XPathElement(XPath.WILDCARD) { 16 | // 17 | // override fun evaluate(t: ParseTree): Collection { 18 | // if (invert) return ArrayList() // !* is weird but valid (empty) 19 | // val kids = ArrayList() 20 | // for (c in Trees.getChildren(t)) { 21 | // kids.add(c as ParseTree) 22 | // } 23 | // return kids 24 | // } 25 | //} 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/test/kotlin/BaseTest.kt: -------------------------------------------------------------------------------- 1 | import kotlin.test.DefaultAsserter 2 | 3 | open class BaseTest { 4 | private val asserter = DefaultAsserter() 5 | 6 | protected fun assertEquals(a: Any?, b: Any?) { 7 | asserter.assertEquals("$a was expected to be equal to $b", a, b) 8 | } 9 | 10 | protected fun assertTrue(a: Boolean) { 11 | asserter.assertTrue("$a was expected to be true", a) 12 | } 13 | 14 | protected fun assertArrayEquals(a: CharArray, b: CharArray) { 15 | assertEquals(a.size, b.size) 16 | for (i in 0 until a.size) { 17 | assertEquals(a[i], b[i]) 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/test/kotlin/LocalListener.kt: -------------------------------------------------------------------------------- 1 | import com.strumenta.minicalc.MiniCalcParser 2 | import com.strumenta.minicalc.MiniCalcParserBaseListener 3 | import org.antlr.v4.kotlinruntime.tree.ParseTree 4 | 5 | /** 6 | * Copyright (c) Martin Gittins 2018. 7 | * User: martingittins 8 | * Date: 13/06/2018 9 | * Time: 09:52 10 | */ 11 | class LocalListener: MiniCalcParserBaseListener() { 12 | 13 | override fun exitMiniCalcFile(ctx: MiniCalcParser.MiniCalcFileContext) { 14 | 15 | ctx.children!!.forEach { line -> 16 | processLine(line) 17 | } 18 | } 19 | 20 | private fun processLine(line: ParseTree) { 21 | processStatement(line.getChild(0)!!) 22 | } 23 | 24 | private fun processStatement(statement: ParseTree) { 25 | val content = statement.getChild(0)!! 26 | when (statement) { 27 | is MiniCalcParser.InputDeclarationStatementContext -> processInputDeclStatement(content) 28 | is MiniCalcParser.VarDeclarationStatementContext -> processVarDeclStatement(content) 29 | is MiniCalcParser.AssignmentStatementContext -> processAssignmentStatement(content) 30 | is MiniCalcParser.PrintStatementContext -> processPrintStatement(content) 31 | } 32 | } 33 | 34 | private fun processPrintStatement(content: ParseTree) { 35 | println("called processPrintStatement") 36 | } 37 | 38 | private fun processAssignmentStatement(content: ParseTree) { 39 | println("called processAssignmentStatement") 40 | } 41 | 42 | private fun processVarDeclStatement(content: ParseTree) { 43 | println("called processVarDeclStatement") 44 | } 45 | 46 | private fun processInputDeclStatement(content: ParseTree) { 47 | println("called processInputDeclStatement") 48 | } 49 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/test/kotlin/StringTest.kt: -------------------------------------------------------------------------------- 1 | import com.strumenta.kotlinmultiplatform.toCharArray 2 | import kotlin.test.Test as test 3 | 4 | class MiscStringTest : BaseTest() { 5 | 6 | @test fun testToCharArrayEmpty() { 7 | assertArrayEquals(charArrayOf(), "".toCharArray()) 8 | } 9 | 10 | @test fun testToCharArrayEmptyLength() { 11 | assertEquals(0, "".toCharArray().size) 12 | } 13 | 14 | @test fun testToCharArrayEmptyEl0() { 15 | assertEquals('a', "abc def".toCharArray()[0]) 16 | } 17 | 18 | @test fun testToCharArray() { 19 | assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray()) 20 | } 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-common/src/test/kotlin/org/antlr/v4/kotlinruntime/misc/IntegerListTest.kt: -------------------------------------------------------------------------------- 1 | package org.antlr.v4.kotlinruntime.misc 2 | 3 | import kotlin.test.assertEquals 4 | import kotlin.test.Test as test 5 | 6 | class IntegerListTest { 7 | 8 | @test fun addToIntegerList() { 9 | val il = IntegerList() 10 | il.add(10) 11 | assertEquals(1, il.size()) 12 | assertEquals(10, il[0]) 13 | } 14 | 15 | @test fun removeAtIntegerList() { 16 | val il = IntegerList() 17 | il.add(10) 18 | il.add(12) 19 | il.add(14) 20 | il.add(16) 21 | il.removeAt(2) 22 | assertEquals(3, il.size()) 23 | assertEquals(10, il[0]) 24 | assertEquals(12, il[1]) 25 | assertEquals(16, il[2]) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = kotlinVersion 3 | 4 | repositories { 5 | mavenCentral() 6 | maven { url "https://plugins.gradle.org/m2/" } 7 | } 8 | dependencies { 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 10 | classpath "gradle.plugin.com.craigburke.gradle:karma-gradle:1.4.4" 11 | } 12 | } 13 | 14 | apply plugin: 'kotlin-platform-js' 15 | apply plugin: 'maven' 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | group = projectGroup 22 | version = projectVersion 23 | 24 | dependencies { 25 | expectedBy project(':antlr-kotlin-runtime-common') 26 | compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion" 27 | compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlinVersion" 28 | testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlinVersion" 29 | } 30 | 31 | compileKotlin2Js.kotlinOptions.moduleKind = "umd" 32 | 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/BitSet.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class BitSet { 4 | 5 | private val setBits = HashSet() 6 | 7 | actual constructor() 8 | 9 | actual fun set(bitIndex: Int) { 10 | if (bitIndex < 0) throw IllegalArgumentException() 11 | setBits.add(bitIndex) 12 | } 13 | actual fun clear(bitIndex: Int) { 14 | if (bitIndex < 0) throw IllegalArgumentException() 15 | setBits.remove(bitIndex) 16 | } 17 | actual fun get(bitIndex: Int): Boolean { 18 | if (bitIndex < 0) throw IllegalArgumentException() 19 | return setBits.contains(bitIndex) 20 | } 21 | 22 | actual fun cardinality(): Int { 23 | return setBits.size 24 | } 25 | 26 | actual fun nextSetBit(i: Int): Int { 27 | val nextSetBits = setBits.filter { it >= i } 28 | return nextSetBits.min() ?: -1 29 | } 30 | 31 | actual fun or(alts: BitSet) { 32 | this.setBits.addAll(alts.setBits) 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/Collections.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual object Collections { 4 | actual fun unmodifiableList(asList: Collection<*>): List<*> { 5 | return asList.toList() 6 | } 7 | 8 | actual fun unmodifiableMap(t: T): U { 9 | TODO("Collections.unmodifiableMap not implemented") //To change body of created functions use File | Settings | File Templates. 10 | } 11 | 12 | actual fun > min(precedencePredicates: List): T { 13 | TODO("Collections.min not implemented") //To change body of created functions use File | Settings | File Templates. 14 | } 15 | 16 | actual fun > max(precedencePredicates: List): T { 17 | TODO("Collections.max not implemented") //To change body of created functions use File | Settings | File Templates. 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | //TODO what is an IdentityHashMap 4 | actual class IdentityHashMap : MutableMap by mutableMapOf() -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/Math.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual object Math { 4 | actual fun min(a: Int, b: Int): Int { 5 | return kotlin.js.Math.min(a, b) 6 | } 7 | 8 | actual fun max(a: Int, b: Int): Int { 9 | return kotlin.js.Math.max(a, b) 10 | } 11 | 12 | actual fun floor(d: Double): Double { 13 | return kotlin.js.Math.floor(d).toDouble() 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/NullPointerException.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class NullPointerException : Throwable { 4 | actual constructor() : super() 5 | actual constructor(message: String) : super(message) 6 | } 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/RuntimeException.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class RuntimeException actual constructor(message: String) : Throwable(message) -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class WeakHashMap constructor(val _wrapped : LinkedHashMap = LinkedHashMap()) : MutableMap by _wrapped { 4 | 5 | actual constructor() : this(LinkedHashMap()) 6 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/arrays.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual fun Array.indices(): List { 4 | TODO("Array.indices not implemented") //To change body of created functions use File | Settings | File Templates. 5 | } 6 | 7 | actual fun IntArray.indices(): List { 8 | TODO("IntArray.indices not implemented") //To change body of created functions use File | Settings | File Templates. 9 | } 10 | 11 | actual fun arraycopy(tokens: Array, p: Int, tokens1: Array, i: Int, i1: Int) { 12 | TODO("arraycopy not implemented") 13 | } 14 | 15 | actual fun Array.clone(): Array { 16 | TODO("Array.clone() not implemented") //To change body of created functions use File | Settings | File Templates. 17 | } 18 | 19 | actual object Arrays { 20 | 21 | actual fun asList(vararg elements: T): List { 22 | return elements.asList() 23 | } 24 | 25 | actual fun copyOf(original: Array, size: Int): Array { 26 | val res = original.copyOf(size) 27 | return res as Array 28 | } 29 | 30 | actual fun equals(a: Array<*>?, b: Array<*>?) : Boolean { 31 | if (a == null) return b == null 32 | if (b == null) return false 33 | if (a.size != b.size) { 34 | return false 35 | } 36 | for (i in 0..a.size) { 37 | if (a[i] != b[i]) { 38 | return false 39 | } 40 | } 41 | return true 42 | } 43 | 44 | actual fun equals(a: IntArray?, b: IntArray?) : Boolean { 45 | if (a == null) return b == null 46 | if (b == null) return false 47 | if (a.size != b.size) { 48 | return false 49 | } 50 | for (i in 0..a.size) { 51 | if (a[i] != b[i]) { 52 | return false 53 | } 54 | } 55 | return true 56 | } 57 | 58 | actual fun toString(a: Array<*>): String { 59 | return "[${a.joinToString(separator = ", ") { it?.toString() ?: "null"}}]" 60 | } 61 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/chars.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | import org.w3c.dom.CharacterData 4 | 5 | actual fun Char.Companion.isSupplementaryCodePoint(codePoint: Int): Boolean { 6 | TODO("Char.Companion.isSupplementaryCodePoint not implemented") //To change body of created functions use File | Settings | File Templates. 7 | } 8 | 9 | actual fun Char.Companion.charCount(i: Int): Byte { 10 | TODO("Char.Companion.charCount not implemented") //To change body of created functions use File | Settings | File Templates. 11 | } 12 | 13 | actual fun Char.Companion.maxValue(): Char { 14 | return '\uFFFF' 15 | } 16 | 17 | actual fun String.toCharArray(): CharArray { 18 | return CharArray(this.length) { 19 | this[it] 20 | } 21 | } 22 | 23 | actual fun Char.Companion.toChars(codePoint: Int, resultArray: CharArray, resultIdx: Int): Int { 24 | TODO("Char.Companion.toChars not implemented") //To change body of created functions use File | Settings | File Templates. 25 | } 26 | 27 | actual fun isCharUppercase(firstChar: Char): Boolean { 28 | if (firstChar.toUpperCase() == firstChar.toLowerCase()) { 29 | return false 30 | } 31 | return firstChar == firstChar.toUpperCase() 32 | } 33 | 34 | actual fun isCharLowerCase(firstChar: Char): Boolean { 35 | if (firstChar.toUpperCase() == firstChar.toLowerCase()) { 36 | return false 37 | } 38 | return firstChar == firstChar.toLowerCase() 39 | } 40 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/logging.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual fun assert(condition: Boolean) { 4 | if (!condition) throw RuntimeException("Assertion failed") 5 | } 6 | 7 | actual fun errMessage(message: String) { 8 | console.error(message) 9 | } 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-js/src/main/kotlin/com/strumenta/kotlinmultiplatform/type.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class Type(val javaClass: JsClass<*>) 4 | 5 | actual fun Type.isInstance(any: Any?): Boolean { 6 | return javaClass.kotlin.isInstance(any) 7 | } 8 | 9 | actual fun TypeDeclarator.getType(name: String) : Type { 10 | //TODO("Type getType is not implemented. TypeDeclarator: $this, name: $name") 11 | 12 | return Type(this.classesByName.find { it.simpleName == name }!!.js) 13 | // var currName = name 14 | // while (currName.startsWith("../")) { 15 | // currName = currName.substring("../".length) 16 | // container = container.kotlin. 17 | // } 18 | //return Type(container.kotlin.nestedClasses.find { it.simpleName == currName }!!) 19 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = kotlinVersion 3 | ext.antlrKotlinVersion = "dssdasd" 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 10 | } 11 | } 12 | 13 | apply plugin: 'kotlin-platform-jvm' 14 | apply plugin: 'maven' 15 | 16 | repositories { 17 | mavenCentral() 18 | } 19 | 20 | antlrKotlinVersion = "dsdasd" 21 | group = projectGroup 22 | version = projectVersion 23 | 24 | dependencies { 25 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 26 | compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" 27 | expectedBy project(":antlr-kotlin-runtime-common") 28 | testCompile "junit:junit:4.12" 29 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion" 30 | testCompile "org.jetbrains.kotlin:kotlin-test:$kotlinVersion" 31 | } 32 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/BitSet.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class BitSet { 4 | private val _wrapped = java.util.BitSet() 5 | 6 | actual constructor() 7 | 8 | actual fun set(bitIndex: Int) { 9 | _wrapped.set(bitIndex) 10 | } 11 | 12 | actual fun clear(bitIndex: Int) { 13 | _wrapped.clear(bitIndex) 14 | } 15 | 16 | actual fun get(bitIndex: Int): Boolean { 17 | return _wrapped.get(bitIndex) 18 | } 19 | 20 | actual fun cardinality(): Int { 21 | return _wrapped.cardinality() 22 | } 23 | 24 | actual fun nextSetBit(i: Int): Int { 25 | return _wrapped.nextSetBit(i) 26 | } 27 | 28 | actual fun or(alts: BitSet) { 29 | return _wrapped.or(alts._wrapped) 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/Collections.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual object Collections { 4 | actual fun unmodifiableList(asList: Collection<*>): List<*> { 5 | return asList.toList() 6 | } 7 | 8 | actual fun unmodifiableMap(t: T): U { 9 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 10 | } 11 | 12 | actual fun > min(precedencePredicates: List): T { 13 | TODO() 14 | } 15 | 16 | actual fun > max(precedencePredicates: List): T { 17 | TODO() 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | // TODO what is an identityhashmap? 4 | actual class IdentityHashMap : MutableMap by emptyMap().toMutableMap() -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/Math.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual object Math { 4 | actual fun min(a: Int, b: Int): Int { 5 | return java.lang.Math.min(a, b) 6 | } 7 | 8 | actual fun max(a: Int, b: Int): Int { 9 | return java.lang.Math.max(a, b) 10 | } 11 | 12 | actual fun floor(d: Double): Double { 13 | return java.lang.Math.floor(d) 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/NullPointerException.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class NullPointerException : Throwable { 4 | actual constructor() : super() 5 | actual constructor(message: String) : super(message) 6 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/RuntimeException.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class RuntimeException actual constructor(message: String) : Throwable(message) -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/UUID.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual class UUID { 4 | 5 | private val _wrapped : java.util.UUID 6 | 7 | actual constructor(most: Long, least: Long) { 8 | _wrapped = java.util.UUID(most, least) 9 | } 10 | 11 | constructor(wrapped: java.util.UUID) { 12 | this._wrapped = wrapped 13 | } 14 | 15 | actual companion object { 16 | actual fun fromString(encoded: String) : UUID { 17 | return UUID(java.util.UUID.fromString(encoded)) 18 | } 19 | } 20 | 21 | override fun equals(other: Any?): Boolean { 22 | return other is UUID && this._wrapped == other._wrapped 23 | } 24 | 25 | override fun hashCode(): Int { 26 | return _wrapped.hashCode() 27 | } 28 | 29 | override fun toString(): String { 30 | return _wrapped.toString() 31 | } 32 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | 4 | actual class WeakHashMap constructor(val _wrapped : java.util.WeakHashMap = java.util.WeakHashMap()) : MutableMap by _wrapped { 5 | 6 | actual constructor() : this(java.util.WeakHashMap()) 7 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/arrays.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual fun Array.indices(): List { 4 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 5 | } 6 | 7 | actual fun IntArray.indices(): List { 8 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 9 | } 10 | 11 | actual fun arraycopy(tokens: Array, p: Int, tokens1: Array, i: Int, i1: Int) { 12 | TODO() 13 | } 14 | 15 | actual fun Array.clone(): Array { 16 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 17 | } 18 | 19 | actual object Arrays { 20 | actual fun asList(vararg elements: T): List { 21 | return java.util.Arrays.asList(*elements) 22 | } 23 | actual fun copyOf(original: Array, size: Int): Array { 24 | return java.util.Arrays.copyOf(original, size) 25 | } 26 | 27 | actual fun equals(a: Array<*>?, b: Array<*>?) : Boolean { 28 | if (a == null) return b == null 29 | if (b == null) return false 30 | return java.util.Arrays.equals(a, b) 31 | } 32 | 33 | actual fun equals(a: IntArray?, b: IntArray?) : Boolean { 34 | if (a == null) return b == null 35 | if (b == null) return false 36 | return java.util.Arrays.equals(a, b) 37 | } 38 | 39 | actual fun toString(a: Array<*>): String { 40 | return java.util.Arrays.toString(a) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/chars.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual fun Char.Companion.isSupplementaryCodePoint(codePoint: Int): Boolean { 4 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 5 | } 6 | 7 | actual fun Char.Companion.charCount(i: Int): Byte { 8 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 9 | } 10 | 11 | actual fun Char.Companion.maxValue() : Char = '\uFFFF' 12 | 13 | actual fun String.toCharArray(): CharArray { 14 | var ca = CharArray(this.length) 15 | this.toCharArray(ca) 16 | return ca 17 | } 18 | 19 | actual fun Char.Companion.toChars(codePoint: Int, resultArray: CharArray, resultIdx: Int): Int { 20 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates. 21 | } 22 | 23 | actual fun isCharUppercase(firstChar: Char): Boolean { 24 | return firstChar.isUpperCase() 25 | } 26 | 27 | actual fun isCharLowerCase(firstChar: Char): Boolean { 28 | return firstChar.isLowerCase() 29 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/logging.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | actual fun assert(condition: Boolean) { 4 | if (!condition) throw AssertionError() 5 | } 6 | 7 | actual fun errMessage(message: String) { 8 | System.err.println(message) 9 | } -------------------------------------------------------------------------------- /antlr-kotlin-runtime-jvm/src/main/kotlin/com/strumenta/kotlinmultiplatform/type.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.kotlinmultiplatform 2 | 3 | import kotlin.reflect.KClass 4 | 5 | actual class Type(val javaClass: KClass<*>) 6 | 7 | actual fun Type.isInstance(any: Any?): Boolean { 8 | return javaClass.isInstance(any) 9 | } 10 | 11 | actual fun TypeDeclarator.getType(name: String) : Type { 12 | return Type(this.classesByName.find { it.simpleName == name }!!) 13 | } -------------------------------------------------------------------------------- /antlr-kotlin-target/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = kotlinVersion 3 | 4 | repositories { 5 | mavenLocal() 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 10 | } 11 | } 12 | 13 | apply plugin: 'kotlin' 14 | apply plugin: 'idea' 15 | apply plugin: 'maven' 16 | 17 | repositories { 18 | mavenLocal() 19 | mavenCentral() 20 | } 21 | 22 | group = projectGroup 23 | version = projectVersion 24 | 25 | dependencies { 26 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 27 | compile group: 'org.antlr', name: 'antlr4', version: antlrVersion 28 | testCompile "junit:junit:4.12" 29 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion" 30 | testCompile "org.jetbrains.kotlin:kotlin-test:$kotlinVersion" 31 | } 32 | -------------------------------------------------------------------------------- /antlr-kotlin-target/src/test/kotlin/Example.kt: -------------------------------------------------------------------------------- 1 | import org.antlr.v4.Tool 2 | import org.antlr.v4.codegen.CodeGenerator 3 | import org.antlr.v4.codegen.Target 4 | import org.antlr.v4.tool.ErrorType 5 | 6 | fun main(args: Array) { 7 | // val language = "Kotlin" 8 | // val targetName = "org.antlr.v4.codegen.target." + language + "Target" 9 | // try { 10 | // val c = Class.forName(targetName).asSubclass(Target::class.java) 11 | // val ctor = c.getConstructor(CodeGenerator::class.java) 12 | // //val cg = CodeGenerator(language) 13 | // //ctor.newInstance(cg) 14 | // println(ctor) 15 | // //val target = ctor.newInstance(this) 16 | // } catch (e: Exception) { 17 | // println("KO $e") 18 | // } 19 | 20 | //Tool.main(arrayOf("-Dlanguage=Kotlin", /*"-o", "/Users/federico/repos/antlr-kotlin-runtime-idea/antlr-kotlin-runtime-examples-jvm/src/main/kotlin",*/ "src/test/resources/MiniCalcLexer.g4")) 21 | Tool.main(arrayOf("-Dlanguage=Kotlin", /*"-o", "/Users/federico/repos/antlr-kotlin-runtime-idea/antlr-kotlin-runtime-examples-jvm/src/main/kotlin",*/ "antlr-kotlin-target/src/test/resources/MiniCalcParser.g4")) 22 | } -------------------------------------------------------------------------------- /antlr-kotlin-target/src/test/resources/MiniCalcLexer.tokens: -------------------------------------------------------------------------------- 1 | NEWLINE=1 2 | WS=2 3 | INPUT=3 4 | VAR=4 5 | PRINT=5 6 | AS=6 7 | INT=7 8 | DECIMAL=8 9 | STRING=9 10 | ID=10 11 | INTLIT=11 12 | DECLIT=12 13 | PLUS=13 14 | MINUS=14 15 | ASTERISK=15 16 | DIVISION=16 17 | ASSIGN=17 18 | LPAREN=18 19 | RPAREN=19 20 | STRING_OPEN=20 21 | UNMATCHED=21 22 | ESCAPE_STRING_DELIMITER=22 23 | ESCAPE_SLASH=23 24 | ESCAPE_NEWLINE=24 25 | ESCAPE_SHARP=25 26 | STRING_CLOSE=26 27 | INTERPOLATION_OPEN=27 28 | STRING_CONTENT=28 29 | INTERPOLATION_CLOSE=29 30 | 'input'=3 31 | 'var'=4 32 | 'print'=5 33 | '\\"'=22 34 | '\\\\'=23 35 | '\\n'=24 36 | '\\#'=25 37 | '#{'=27 38 | '}'=29 39 | -------------------------------------------------------------------------------- /antlr-kotlin-target/src/test/resources/MiniCalcParser.g4: -------------------------------------------------------------------------------- 1 | parser grammar MiniCalcParser; 2 | 3 | options { tokenVocab=MiniCalcLexer; } 4 | 5 | miniCalcFile : lines=line+ ; 6 | 7 | line : statement (NEWLINE | EOF) ; 8 | 9 | statement : inputDeclaration # inputDeclarationStatement 10 | | varDeclaration # varDeclarationStatement 11 | | assignment # assignmentStatement 12 | | print # printStatement ; 13 | 14 | print : PRINT LPAREN expression RPAREN ; 15 | 16 | inputDeclaration : INPUT type name=ID ; 17 | 18 | varDeclaration : VAR assignment ; 19 | 20 | assignment : ID ASSIGN expression ; 21 | 22 | expression : left=expression operator=(DIVISION|ASTERISK) right=expression # binaryOperation 23 | | left=expression operator=(PLUS|MINUS) right=expression # binaryOperation 24 | | value=expression AS targetType=type # typeConversion 25 | | LPAREN expression RPAREN # parenExpression 26 | | ID # valueReference 27 | | MINUS expression # minusExpression 28 | | STRING_OPEN (parts+=stringLiteralContent)* STRING_CLOSE # stringLiteral 29 | | INTLIT # intLiteral 30 | | DECLIT # decimalLiteral ; 31 | 32 | stringLiteralContent : STRING_CONTENT # constantString 33 | | INTERPOLATION_OPEN expression INTERPOLATION_CLOSE # interpolatedValue ; 34 | 35 | type : INT # integer 36 | | DECIMAL # decimal 37 | | STRING # string ; 38 | -------------------------------------------------------------------------------- /antlr-kotlin-target/src/test/resources/MiniCalcParser.tokens: -------------------------------------------------------------------------------- 1 | NEWLINE=1 2 | WS=2 3 | INPUT=3 4 | VAR=4 5 | PRINT=5 6 | AS=6 7 | INT=7 8 | DECIMAL=8 9 | STRING=9 10 | ID=10 11 | INTLIT=11 12 | DECLIT=12 13 | PLUS=13 14 | MINUS=14 15 | ASTERISK=15 16 | DIVISION=16 17 | ASSIGN=17 18 | LPAREN=18 19 | RPAREN=19 20 | STRING_OPEN=20 21 | UNMATCHED=21 22 | ESCAPE_STRING_DELIMITER=22 23 | ESCAPE_SLASH=23 24 | ESCAPE_NEWLINE=24 25 | ESCAPE_SHARP=25 26 | STRING_CLOSE=26 27 | INTERPOLATION_OPEN=27 28 | STRING_CONTENT=28 29 | INTERPOLATION_CLOSE=29 30 | 'input'=3 31 | 'var'=4 32 | 'print'=5 33 | '\\"'=22 34 | '\\\\'=23 35 | '\\n'=24 36 | '\\#'=25 37 | '#{'=27 38 | '}'=29 39 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | projectVersion=0.0.2 2 | projectGroup=com.strumenta.antlr-kotlin 3 | kotlinVersion=1.2.60 4 | antlrVersion=4.7.1 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ftomassetti/antlr-kotlin/2b705f480ed0f62c7504ef02828fa15b4ca6223c/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Aug 16 10:52:26 CEST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip 7 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'antlr-kotlin' 2 | 3 | include 'antlr-kotlin-runtime-common', 'antlr-kotlin-runtime-jvm', 'antlr-kotlin-runtime-js', 'antlr-kotlin-target', 'antlr-kotlin-gradle-plugin' 4 | --------------------------------------------------------------------------------