├── .editorconfig ├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE-Apache ├── LICENSE-BSD ├── README.md ├── antlr-kotlin-benchmarks ├── antlr │ └── mysql │ │ ├── MySQLLexer.g4 │ │ ├── MySQLParser.g4 │ │ └── predefined.tokens ├── build.gradle.kts └── src │ ├── commonMain │ ├── kotlin │ │ └── org │ │ │ └── antlr │ │ │ └── v4 │ │ │ └── kotlinruntime │ │ │ └── benchmarks │ │ │ ├── IO.kt │ │ │ └── mysql │ │ │ ├── MySQLBaseLexer.kt │ │ │ ├── MySQLBaseRecognizer.kt │ │ │ ├── MySQLBenchmarks.kt │ │ │ ├── MySQLErrorListener.kt │ │ │ ├── MySQLRecognizerCommon.kt │ │ │ ├── SqlMode.kt │ │ │ └── util │ │ │ ├── StatementFinishState.kt │ │ │ ├── StatementSpan.kt │ │ │ ├── TextSpan.kt │ │ │ └── VersionCheckResult.kt │ └── resources │ │ └── mysql │ │ ├── bitrix_queries_cut.sql │ │ ├── sakila-data.sql │ │ └── statements.txt │ ├── jsMain │ └── kotlin │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── benchmarks │ │ ├── IO.kt │ │ └── node.kt │ ├── jvmMain │ └── kotlin │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── benchmarks │ │ └── IO.kt │ ├── nativeMain │ └── kotlin │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── benchmarks │ │ └── IO.kt │ └── wasmJsMain │ └── kotlin │ └── org │ └── antlr │ └── v4 │ └── kotlinruntime │ └── benchmarks │ └── IO.kt ├── antlr-kotlin-gradle-plugin ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── com │ └── strumenta │ └── antlrkotlin │ └── gradle │ ├── AntlrKotlinPlugin.kt │ ├── AntlrKotlinTask.kt │ └── internal │ ├── Antlr4Tool.kt │ ├── AntlrExecutor.kt │ ├── AntlrResult.kt │ ├── AntlrSourceGenerationException.kt │ ├── AntlrSpec.kt │ ├── AntlrSpecFactory.kt │ ├── AntlrTool.kt │ └── AntlrWorkerManager.kt ├── antlr-kotlin-runtime ├── build.gradle.kts └── src │ ├── androidNativeMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ └── Console.kt │ ├── appleMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ └── Console.kt │ ├── commonMain │ └── kotlin │ │ ├── com │ │ └── strumenta │ │ │ └── antlrkotlin │ │ │ └── runtime │ │ │ ├── Assert.kt │ │ │ ├── BitSet.kt │ │ │ ├── CodePoint.kt │ │ │ ├── Collections.kt │ │ │ ├── Console.kt │ │ │ ├── CopyOnWriteArrayList.kt │ │ │ ├── Environment.kt │ │ │ ├── IdentityHashMap.kt │ │ │ ├── JsName.kt │ │ │ ├── LineReader.kt │ │ │ ├── SimpleBitSet.kt │ │ │ ├── StringLineReader.kt │ │ │ ├── Synchronized.kt │ │ │ ├── System.kt │ │ │ ├── WeakHashMap.kt │ │ │ └── ext │ │ │ ├── Appendable.ext.kt │ │ │ ├── Array.ext.kt │ │ │ ├── Char.ext.kt │ │ │ ├── Int.ext.kt │ │ │ └── String.ext.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ ├── ANTLRErrorListener.kt │ │ ├── ANTLRErrorStrategy.kt │ │ ├── ANTLRInputStream.kt │ │ ├── AbstractCharStreams.kt │ │ ├── BailErrorStrategy.kt │ │ ├── BaseErrorListener.kt │ │ ├── BufferedTokenStream.kt │ │ ├── CharStream.kt │ │ ├── CharStreams.kt │ │ ├── CommonToken.kt │ │ ├── CommonTokenFactory.kt │ │ ├── CommonTokenStream.kt │ │ ├── ConsoleErrorListener.kt │ │ ├── DefaultErrorStrategy.kt │ │ ├── DiagnosticErrorListener.kt │ │ ├── DummyCharStream.kt │ │ ├── DummyTokenStream.kt │ │ ├── EmptyStackException.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 │ │ ├── StringCharStream.kt │ │ ├── Token.kt │ │ ├── TokenFactory.kt │ │ ├── TokenSource.kt │ │ ├── TokenStream.kt │ │ ├── TokenStreamRewriter.kt │ │ ├── UnbufferedTokenStream.kt │ │ ├── Vocabulary.kt │ │ ├── VocabularyImpl.kt │ │ ├── WritableToken.kt │ │ ├── ast │ │ ├── Node.kt │ │ ├── Point.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 │ │ ├── MultiMap.kt │ │ ├── MurmurHash.kt │ │ ├── ObjectEqualityComparator.kt │ │ ├── OrderedHashSet.kt │ │ ├── ParseCancellationException.kt │ │ ├── Predicate.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 │ ├── commonTest │ └── kotlin │ │ ├── StringTest.kt │ │ ├── com │ │ └── strumenta │ │ │ └── antlrkotlin │ │ │ └── runtime │ │ │ └── BitSetTest.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ ├── CharStreamsTest.kt │ │ ├── StringCharStreamTest.kt │ │ └── misc │ │ └── IntegerListTest.kt │ ├── jsAndWasmSharedMain │ └── kotlin │ │ ├── com │ │ └── strumenta │ │ │ └── antlrkotlin │ │ │ └── runtime │ │ │ ├── CopyOnWriteArrayList.kt │ │ │ ├── Synchronized.kt │ │ │ └── WeakHashMap.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── CharStreams.kt │ ├── jsMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ ├── BitSet.kt │ │ ├── Console.kt │ │ ├── Environment.kt │ │ ├── IdentityEntriesView.kt │ │ ├── IdentityHashMap.kt │ │ ├── IdentityKeysView.kt │ │ ├── IdentityValuesView.kt │ │ ├── JsMap.kt │ │ ├── JsName.kt │ │ └── JsUtils.kt │ ├── jsTest │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ └── IdentityHashMapTests.kt │ ├── jvmMain │ └── kotlin │ │ ├── com │ │ └── strumenta │ │ │ └── antlrkotlin │ │ │ └── runtime │ │ │ ├── BitSet.kt │ │ │ ├── Console.kt │ │ │ ├── CopyOnWriteArrayList.kt │ │ │ ├── Environment.kt │ │ │ ├── IdentityHashMap.kt │ │ │ ├── JsName.kt │ │ │ ├── Synchronized.kt │ │ │ └── WeakHashMap.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── CharStreams.kt │ ├── linuxMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ └── Console.kt │ ├── mingwMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ └── Console.kt │ ├── nativeMain │ └── kotlin │ │ ├── com │ │ └── strumenta │ │ │ └── antlrkotlin │ │ │ └── runtime │ │ │ ├── BitSet.kt │ │ │ ├── Console.kt │ │ │ ├── CopyOnWriteArrayList.kt │ │ │ ├── Environment.kt │ │ │ ├── IdentityHashMap.kt │ │ │ ├── JsName.kt │ │ │ ├── Synchronized.kt │ │ │ └── WeakHashMap.kt │ │ └── org │ │ └── antlr │ │ └── v4 │ │ └── kotlinruntime │ │ └── CharStreams.kt │ ├── wasmJsMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ ├── BitSet.kt │ │ ├── Console.kt │ │ ├── Environment.kt │ │ ├── IdentityHashMap.kt │ │ ├── IsNodeJs.kt │ │ └── JsName.kt │ └── wasmWasiMain │ └── kotlin │ ├── com │ └── strumenta │ │ └── antlrkotlin │ │ └── runtime │ │ ├── BitSet.kt │ │ ├── Console.kt │ │ ├── CopyOnWriteArrayList.kt │ │ ├── Environment.kt │ │ ├── IdentityHashMap.kt │ │ ├── JsName.kt │ │ ├── Synchronized.kt │ │ └── WeakHashMap.kt │ └── org │ └── antlr │ └── v4 │ └── kotlinruntime │ └── CharStreams.kt ├── antlr-kotlin-target ├── build.gradle.kts └── src │ └── main │ ├── kotlin │ └── org │ │ └── antlr │ │ └── v4 │ │ └── codegen │ │ └── target │ │ └── KotlinTarget.kt │ └── resources │ └── org │ └── antlr │ └── v4 │ └── tool │ └── templates │ └── codegen │ └── Kotlin │ └── Kotlin.stg ├── antlr-kotlin-tests ├── antlr │ ├── CPP14Lexer.g4 │ ├── CPP14Parser.g4 │ ├── MiniCalcLexer.g4 │ ├── MiniCalcParser.g4 │ ├── SimpleExpr.g4 │ ├── SizedList.g4 │ ├── TSqlLexer.g4 │ ├── TSqlParser.g4 │ ├── VisualBasic6Lexer.g4 │ ├── VisualBasic6Parser.g4 │ ├── XPathExpr.g4 │ ├── XPathLexer.g4 │ ├── css3Lexer.g4 │ └── css3Parser.g4 ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── test │ │ └── CPP14ParserBase.kt │ ├── commonTest │ ├── kotlin │ │ ├── com │ │ │ └── strumenta │ │ │ │ └── antlrkotlin │ │ │ │ ├── test │ │ │ │ ├── GrammarTest.kt │ │ │ │ ├── SyntaxErrorsErrorListener.kt │ │ │ │ ├── ThrowingErrorListener.kt │ │ │ │ ├── grammars │ │ │ │ │ ├── CPP14GrammarTest.kt │ │ │ │ │ ├── Css3GrammarTest.kt │ │ │ │ │ ├── SizedListGrammarTest.kt │ │ │ │ │ └── Vb6GrammarTest.kt │ │ │ │ ├── minicalc │ │ │ │ │ ├── LocalListener.kt │ │ │ │ │ ├── MiniCalcLexerTest.kt │ │ │ │ │ └── MiniCalcParserTest.kt │ │ │ │ └── xpath │ │ │ │ │ └── XPathTest.kt │ │ │ │ └── util │ │ │ │ └── Resources.kt │ │ └── org │ │ │ └── antlr │ │ │ └── v4 │ │ │ └── kotlinruntime │ │ │ └── misc │ │ │ └── InterpreterDataReaderTest.kt │ └── resources │ │ ├── cpp │ │ ├── macro.cpp │ │ ├── macro.cpp.tree │ │ ├── test.cpp │ │ └── test.cpp.tree │ │ ├── css3 │ │ ├── at-rule.css │ │ └── at-rule.css.tree │ │ ├── sizedList │ │ ├── five.sl │ │ ├── five.sl.tree │ │ ├── oneTooMany.sl │ │ └── oneTooMany.sl.errors │ │ ├── test.interp │ │ ├── tsql │ │ ├── constants.sql │ │ ├── constants.sql.errors │ │ ├── hints.sql │ │ └── hints.sql.tree │ │ └── vb6 │ │ ├── form1.vb │ │ └── form1.vb.errors │ ├── jsTest │ └── kotlin │ │ └── com │ │ └── strumenta │ │ └── antlrkotlin │ │ └── test │ │ └── grammars │ │ └── TSqlGrammarJsTest.kt │ └── nativeTest │ └── kotlin │ └── com │ └── strumenta │ └── antlrkotlin │ └── test │ └── grammars │ └── TSqlGrammarNativeTest.kt ├── build.gradle.kts ├── buildSrc ├── build.gradle.kts ├── gradle.properties ├── settings.gradle.kts └── src │ └── main │ └── kotlin │ └── com │ └── strumenta │ └── antlrkotlin │ └── gradle │ ├── ext │ ├── MavenPublishBaseExtension.ext.kt │ └── Project.ext.kt │ └── plugins │ ├── StrumentaGradlePluginModulePlugin.kt │ ├── StrumentaJvmLibraryModulePlugin.kt │ ├── StrumentaMultiplatformModuleExtension.kt │ └── StrumentaMultiplatformModulePlugin.kt ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kotlin-js-store └── yarn.lock └── settings.gradle.kts /LICENSE-BSD: -------------------------------------------------------------------------------- 1 | Copyright 2024 ANTLR Kotlin contributors 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/IO.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks 4 | 5 | public expect fun readBenchmarkFile(name: String): String 6 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/MySQLBaseRecognizer.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql 4 | 5 | import org.antlr.v4.kotlinruntime.Parser 6 | import org.antlr.v4.kotlinruntime.TokenStream 7 | 8 | @Suppress("MemberVisibilityCanBePrivate") 9 | public abstract class MySQLBaseRecognizer(input: TokenStream) : Parser(input), MySQLRecognizerCommon { 10 | public override var serverVersion: Int = 0 11 | public override var sqlModes: MutableSet = HashSet() 12 | 13 | /** 14 | * Determines if the given SQL mode is currently active in the lexer. 15 | * 16 | * @param mode The mode to check 17 | * @return `true` if the mode is one of the currently active modes, `false` otherwise 18 | */ 19 | public override fun isSqlModeActive(mode: SqlMode): Boolean = 20 | sqlModes.contains(mode) 21 | 22 | public override fun sqlModeFromString(modes: String): Unit = 23 | throw UnsupportedOperationException("sqlModeFromString not implemented") 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/MySQLRecognizerCommon.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql 4 | 5 | /** 6 | * Describes functionality found in both lexer and parser classes. 7 | */ 8 | public interface MySQLRecognizerCommon { 9 | // To parameterize the parsing process 10 | public val serverVersion: Int 11 | public val sqlModes: Set 12 | 13 | // Returns true if the given mode (one of the enums above) is set 14 | public fun isSqlModeActive(mode: SqlMode): Boolean 15 | public fun sqlModeFromString(modes: String) 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/SqlMode.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql 4 | 5 | /** 6 | * SQL modes that control parsing behavior. 7 | */ 8 | public enum class SqlMode { 9 | NoMode, 10 | AnsiQuotes, 11 | HighNotPrecedence, 12 | PipesAsConcat, 13 | IgnoreSpace, 14 | NoBackslashEscapes, 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/util/StatementFinishState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql.util 4 | 5 | /** 6 | * Indicates how a statement ends. 7 | */ 8 | public enum class StatementFinishState { 9 | /** 10 | * Ends with a delimiter. 11 | */ 12 | Complete, 13 | 14 | /** 15 | * Ends with an open comment (multiline or single line w/o following new line). 16 | */ 17 | OpenComment, 18 | 19 | /** 20 | * A string (single, double or backtick quoted) wasn't closed. 21 | */ 22 | OpenString, 23 | 24 | /** 25 | * The delimiter is missing. 26 | */ 27 | NoDelimiter, 28 | 29 | /** 30 | * The statement changes the delimiter. 31 | */ 32 | DelimiterChange, 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/util/StatementSpan.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql.util 4 | 5 | public data class StatementSpan( 6 | /** 7 | * The delimiter with which this statement ended or undefined if no delimiter was found. 8 | */ 9 | val delimiter: String? = null, 10 | 11 | /** 12 | * Start and length of the entire statement, including leading whitespaces. 13 | */ 14 | val span: TextSpan, 15 | 16 | /** 17 | * TODO 18 | */ 19 | val contentStart: Int, 20 | 21 | /** 22 | * The offset where non-whitespace content starts. 23 | */ 24 | val state: StatementFinishState, 25 | ) 26 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/util/TextSpan.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql.util 4 | 5 | public data class TextSpan( 6 | val start: Int, 7 | val length: Int, 8 | ) 9 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/mysql/util/VersionCheckResult.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks.mysql.util 4 | 5 | /** 6 | * Information about a statement with version information. 7 | */ 8 | public data class VersionCheckResult( 9 | /** 10 | * True if the version in the statement matched a given version. 11 | */ 12 | val matched: Boolean, 13 | 14 | /** 15 | * The statement with stripped version information. 16 | */ 17 | val statement: String, 18 | 19 | /** 20 | * The found version. Can be 0 if the statement contains no version. 21 | */ 22 | val version: Int, 23 | ) 24 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/jsMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/IO.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks 4 | 5 | // TODO(Edoardo): this should probably be replaced by a Gradle task, 6 | // but in the meantime it should work consistently 7 | private const val basePath = "../../../../antlr-kotlin-benchmarks/build/processedResources/js/main" 8 | 9 | public actual fun readBenchmarkFile(name: String): String { 10 | val options = js("({ encoding: 'utf8' })") 11 | return readFileSync("$basePath$name", options) 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/jsMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/node.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | @file:JsModule("node:fs") 4 | 5 | package org.antlr.v4.kotlinruntime.benchmarks 6 | 7 | internal external fun readFileSync(path: String, options: dynamic): String 8 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/jvmMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/IO.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks 4 | 5 | import java.lang.invoke.MethodHandles 6 | 7 | public actual fun readBenchmarkFile(name: String): String { 8 | val clazz = MethodHandles.lookup().lookupClass() 9 | val stream = clazz.getResourceAsStream(name)!! 10 | return stream.bufferedReader().readText() 11 | } 12 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/nativeMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/IO.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks 4 | 5 | import kotlinx.io.buffered 6 | import kotlinx.io.files.Path 7 | import kotlinx.io.files.SystemFileSystem 8 | import kotlinx.io.readString 9 | import kotlin.experimental.ExperimentalNativeApi 10 | import kotlin.native.CpuArchitecture.ARM64 11 | import kotlin.native.CpuArchitecture.X64 12 | import kotlin.native.OsFamily.* 13 | 14 | @OptIn(ExperimentalNativeApi::class) 15 | private val arch: String = 16 | when (Platform.cpuArchitecture) { 17 | X64 -> "X64" 18 | ARM64 -> "Arm64" 19 | else -> throw IllegalStateException("Unsupported CPU architecture") 20 | } 21 | 22 | @OptIn(ExperimentalNativeApi::class) 23 | private val dir: String = 24 | when (Platform.osFamily) { 25 | WINDOWS -> "mingw$arch" 26 | LINUX -> "linux$arch" 27 | MACOSX -> "macos$arch" 28 | else -> throw IllegalStateException("Unsupported OS family") 29 | } 30 | 31 | // TODO(Edoardo): this should probably be replaced by a Gradle task, 32 | // but in the meantime it should work consistently 33 | private val basePath = "antlr-kotlin-benchmarks/build/processedResources/$dir/main" 34 | 35 | public actual fun readBenchmarkFile(name: String): String { 36 | val path = Path("$basePath$name") 37 | val source = SystemFileSystem.source(path).buffered() 38 | return source.readString() 39 | } 40 | -------------------------------------------------------------------------------- /antlr-kotlin-benchmarks/src/wasmJsMain/kotlin/org/antlr/v4/kotlinruntime/benchmarks/IO.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.benchmarks 4 | 5 | // TODO(Edoardo): this should probably be replaced by a Gradle task, 6 | // but in the meantime it should work consistently 7 | private const val basePath = "../../../../antlr-kotlin-benchmarks/build/processedResources/wasmJs/main" 8 | 9 | @Suppress("UNUSED_PARAMETER") 10 | private fun readFileSync(name: String): String = 11 | js( 12 | """ 13 | { 14 | const fs = require('fs'); 15 | return fs.readFileSync(name, { 16 | encoding: 'utf8' 17 | }); 18 | } 19 | """ 20 | ) 21 | 22 | public actual fun readBenchmarkFile(name: String): String = 23 | readFileSync("$basePath$name") 24 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("UnstableApiUsage") 2 | 3 | plugins { 4 | id("strumenta.gradle.plugin") 5 | } 6 | 7 | dependencies { 8 | implementation(libs.antlr4) 9 | implementation(projects.antlrKotlinTarget) 10 | } 11 | 12 | gradlePlugin { 13 | website = "https://github.com/Strumenta/antlr-kotlin" 14 | vcsUrl = "https://github.com/Strumenta/antlr-kotlin" 15 | 16 | plugins { 17 | create("StrumentaAntlrKotlin") { 18 | id = "com.strumenta.antlr-kotlin" 19 | displayName = "Support ANTLR Kotlin" 20 | description = "The ANTLR Gradle plugin for the Kotlin target" 21 | tags = listOf("antlr", "antlr4", "kotlin", "multiplatform") 22 | implementationClass = "com.strumenta.antlrkotlin.gradle.AntlrKotlinPlugin" 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/AntlrKotlinPlugin.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle 4 | 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | 8 | public class AntlrKotlinPlugin : Plugin { 9 | public override fun apply(target: Project) { 10 | // Noop 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/Antlr4Tool.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import org.gradle.internal.reflect.JavaMethod 6 | import java.io.File 7 | 8 | internal class Antlr4Tool : AntlrTool() { 9 | override fun invoke(arguments: List, inputDirectory: File?): Int { 10 | val backedObject = loadTool("org.antlr.v4.Tool", arguments.toTypedArray()) 11 | 12 | if (inputDirectory != null) { 13 | setField(backedObject, "inputDirectory", inputDirectory) 14 | } 15 | 16 | JavaMethod.of(backedObject, Void::class.javaObjectType, "processGrammarsOnCommandLine").invoke(backedObject) 17 | return JavaMethod.of(backedObject, Int::class.javaObjectType, "getNumErrors").invoke(backedObject) 18 | } 19 | 20 | override fun available(): Boolean { 21 | try { 22 | loadTool("org.antlr.v4.Tool", null) 23 | return true 24 | } catch (_: ClassNotFoundException) { 25 | // Ignored 26 | } 27 | 28 | return false 29 | } 30 | 31 | @Suppress("SameParameterValue") 32 | private fun setField(obj: Any, fieldName: String, value: File) { 33 | val field = obj.javaClass.getField(fieldName) 34 | field.isAccessible = true 35 | field[obj] = value 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/AntlrExecutor.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import org.gradle.process.internal.worker.RequestHandler 6 | import org.slf4j.LoggerFactory 7 | 8 | internal class AntlrExecutor : RequestHandler { 9 | private companion object { 10 | private const val serialVersionUID = 1L 11 | private val logger = LoggerFactory.getLogger(AntlrExecutor::class.java) 12 | } 13 | 14 | override fun run(spec: AntlrSpec): AntlrResult { 15 | val antlrTool = Antlr4Tool() 16 | 17 | if (antlrTool.available()) { 18 | logger.info("Processing with ANTLR 4") 19 | return antlrTool.process(spec) 20 | } 21 | 22 | throw IllegalStateException("No ANTLR 4 implementation available") 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/AntlrResult.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import java.io.Serializable 6 | 7 | internal data class AntlrResult( 8 | val errorCount: Int, 9 | val exception: Exception? = null, 10 | ) : Serializable { 11 | private companion object { 12 | private const val serialVersionUID = 1L 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/AntlrSourceGenerationException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import org.gradle.api.GradleException 6 | import org.gradle.internal.exceptions.Contextual 7 | 8 | @Contextual 9 | internal class AntlrSourceGenerationException(message: String, cause: Throwable?) : GradleException(message, cause) { 10 | private companion object { 11 | private const val serialVersionUID = 1L 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/AntlrSpec.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import java.io.File 6 | import java.io.Serializable 7 | import java.util.* 8 | 9 | internal data class AntlrSpec( 10 | val arguments: List, 11 | val grammarFiles: Set, 12 | val inputDirectories: Set, 13 | val outputDirectory: File, 14 | val maxHeapSize: String, 15 | ) : Serializable { 16 | private companion object { 17 | private const val serialVersionUID = 1L 18 | } 19 | 20 | fun asArgumentsWithFiles(): List { 21 | val commandLine = LinkedList(arguments) 22 | commandLine.add("-Dlanguage=Kotlin") 23 | commandLine.add("-o") 24 | commandLine.add(outputDirectory.absolutePath) 25 | 26 | for (file in grammarFiles) { 27 | commandLine.add(file.absolutePath) 28 | } 29 | 30 | return commandLine 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-gradle-plugin/src/main/kotlin/com/strumenta/antlrkotlin/gradle/internal/AntlrSpecFactory.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.gradle.internal 4 | 5 | import com.strumenta.antlrkotlin.gradle.AntlrKotlinTask 6 | import org.gradle.api.file.FileCollection 7 | import java.io.File 8 | import java.util.* 9 | 10 | internal class AntlrSpecFactory { 11 | fun create( 12 | antlrTask: AntlrKotlinTask, 13 | grammarFiles: Set, 14 | sourceSetDirectories: FileCollection?, 15 | ): AntlrSpec { 16 | val arguments = LinkedList(antlrTask.arguments) 17 | val packageName = antlrTask.packageName 18 | 19 | if (packageName != null) { 20 | arguments.add("-package") 21 | arguments.add(packageName) 22 | } 23 | 24 | if (antlrTask.isTrace) { 25 | arguments.add("-trace") 26 | } 27 | 28 | if (antlrTask.isTraceLexer) { 29 | arguments.add("-traceLexer") 30 | } 31 | 32 | if (antlrTask.isTraceParser) { 33 | arguments.add("-traceParser") 34 | } 35 | 36 | if (antlrTask.isTraceTreeWalker) { 37 | arguments.add("-traceTreeWalker") 38 | } 39 | 40 | // See https://github.com/Strumenta/antlr-kotlin/issues/85 41 | arguments.add("-encoding") 42 | arguments.add(antlrTask.encoding) 43 | 44 | val sourceSetDirectoriesFiles = 45 | if (sourceSetDirectories == null) { 46 | emptySet() 47 | } else { 48 | sourceSetDirectories.files 49 | } 50 | 51 | return AntlrSpec( 52 | arguments, 53 | grammarFiles, 54 | sourceSetDirectoriesFiles, 55 | antlrTask.outputDirectory!!, 56 | antlrTask.maxHeapSize, 57 | ) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.strumenta.antlrkotlin.gradle.ext.setupPom 2 | import com.strumenta.antlrkotlin.gradle.ext.targetsNative 3 | import com.vanniktech.maven.publish.SonatypeHost 4 | import org.jetbrains.dokka.Platform 5 | import org.jetbrains.dokka.gradle.DokkaTask 6 | 7 | plugins { 8 | id("strumenta.multiplatform") 9 | id("org.jetbrains.dokka") 10 | } 11 | 12 | strumentaMultiplatform { 13 | applyJvm() 14 | applyJs() 15 | applyWasi() 16 | 17 | // Opting-in for native targets should be explicit, 18 | // as it makes the build and test process slower. 19 | // 20 | // Opt in by setting 'target.is.native = true' in gradle.properties 21 | if (targetsNative()) { 22 | applyNative() 23 | } 24 | } 25 | 26 | kotlin { 27 | sourceSets { 28 | commonTest { 29 | dependencies { 30 | implementation(kotlin("test")) 31 | } 32 | } 33 | } 34 | } 35 | 36 | mavenPublishing { 37 | coordinates( 38 | groupId = project.group as String, 39 | artifactId = project.name, 40 | version = project.version as String, 41 | ) 42 | 43 | setupPom(project, projectDescription = "Runtime for ANTLR Kotlin") 44 | publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, true) 45 | signAllPublications() 46 | } 47 | 48 | tasks.withType().configureEach { 49 | dokkaSourceSets { 50 | configureEach { 51 | suppress = true 52 | } 53 | 54 | val commonMain by getting { 55 | suppress = false 56 | platform = Platform.jvm 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/androidNativeMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import platform.android.ANDROID_LOG_ERROR 6 | import platform.android.__android_log_print 7 | 8 | internal actual fun androidPrintErr(message: String) { 9 | __android_log_print(ANDROID_LOG_ERROR.toInt(), "antlr-kotlin", message) 10 | } 11 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/appleMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual fun androidPrintErr(message: String): Unit = error("Should not be called") 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/Assert.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlin.contracts.ExperimentalContracts 6 | import kotlin.contracts.contract 7 | 8 | /** 9 | * Throws an [AssertionError] if the [condition] is `false`. 10 | */ 11 | @OptIn(ExperimentalContracts::class) 12 | @Suppress("NOTHING_TO_INLINE", "KotlinRedundantDiagnosticSuppress") 13 | internal inline fun assert(condition: Boolean, message: String? = null) { 14 | contract { 15 | returns() implies condition 16 | } 17 | 18 | if (!condition) { 19 | throw AssertionError(message) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/CodePoint.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // Note: Kotlin Native has constants named in the same way. 6 | // The _ suffix prevents the conflicts 7 | internal const val MIN_SUPPLEMENTARY_CODE_POINT_: Int = 0x10000 8 | internal const val MAX_CODE_POINT_: Int = 0x10FFFF 9 | internal const val MIN_HIGH_SURROGATE: Int = 0xD800 10 | internal const val MIN_LOW_SURROGATE: Int = 0xDC00 11 | internal const val HIGH_SURROGATE_ENCODE_OFFSET: Int = 12 | (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT_ ushr 10)) 13 | 14 | internal fun isBmpCodePoint(codePoint: Int): Boolean = 15 | codePoint ushr 16 == 0 16 | 17 | internal fun highSurrogate(codePoint: Int): Char = 18 | ((codePoint ushr 10) + HIGH_SURROGATE_ENCODE_OFFSET).toChar() 19 | 20 | internal fun lowSurrogate(codePoint: Int): Char = 21 | ((codePoint and 0x3FF) + MIN_LOW_SURROGATE).toChar() 22 | 23 | internal fun isValidCodePoint(codePoint: Int): Boolean = 24 | codePoint in 0..MAX_CODE_POINT_ 25 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/Collections.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal object Collections { 6 | fun > min(collection: Collection): T = 7 | collection.minOrNull() ?: throw NoSuchElementException() 8 | 9 | fun > max(collection: Collection): T = 10 | collection.maxOrNull() ?: throw NoSuchElementException() 11 | } 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | /** 6 | * Prints the line separator to the standard error stream. 7 | */ 8 | internal expect fun platformPrintErrLn() 9 | 10 | /** 11 | * Prints the give error message and the line separator to the standard error stream. 12 | */ 13 | internal expect fun platformPrintErrLn(message: String) 14 | 15 | /** 16 | * Prints the give error message to the standard error stream. 17 | */ 18 | internal expect fun platformPrintErr(message: String) 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/CopyOnWriteArrayList.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal expect class CopyOnWriteArrayList() : MutableList { 6 | // Convenience constructor to avoid initializing with mutable state 7 | constructor(elements: Collection) 8 | 9 | override val size: Int 10 | override fun contains(element: E): Boolean 11 | override fun containsAll(elements: Collection): Boolean 12 | override fun get(index: Int): E 13 | override fun indexOf(element: E): Int 14 | override fun isEmpty(): Boolean 15 | override fun iterator(): MutableIterator 16 | override fun lastIndexOf(element: E): Int 17 | override fun add(element: E): Boolean 18 | override fun add(index: Int, element: E) 19 | override fun addAll(index: Int, elements: Collection): Boolean 20 | override fun addAll(elements: Collection): Boolean 21 | override fun clear() 22 | override fun listIterator(): MutableListIterator 23 | override fun listIterator(index: Int): MutableListIterator 24 | override fun remove(element: E): Boolean 25 | override fun removeAll(elements: Collection): Boolean 26 | override fun removeAt(index: Int): E 27 | override fun retainAll(elements: Collection): Boolean 28 | override fun set(index: Int, element: E): E 29 | override fun subList(fromIndex: Int, toIndex: Int): MutableList 30 | } 31 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/Environment.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | /** 6 | * Gets the value of the specified environment variable. 7 | * 8 | * An environment variable is a system-dependent external named value. 9 | * 10 | * @param name The name of the environment variable 11 | * @return The string value of the variable, or `null` 12 | * if the variable is not defined in the system environment 13 | * 14 | * @author Edoardo Luppi 15 | */ 16 | internal expect fun platformGetEnv(name: String): String? 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal expect class IdentityHashMap() : MutableMap { 6 | override val size: Int 7 | override val entries: MutableSet> 8 | override val keys: MutableSet 9 | override val values: MutableCollection 10 | override fun containsKey(key: K): Boolean 11 | override fun containsValue(value: V): Boolean 12 | override fun get(key: K): V? 13 | override fun isEmpty(): Boolean 14 | override fun clear() 15 | override fun put(key: K, value: V): V? 16 | override fun putAll(from: Map) 17 | override fun remove(key: K): V? 18 | } 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | /** 6 | * A typealias for Kotlin's `JsName` in the `js` and `wasmJs` targets, 7 | * and a non-retained annotation for all the other targets. 8 | * 9 | * It should be used **only** in `Kotlin.stg`. 10 | * 11 | * See [issues/175](https://github.com/Strumenta/antlr-kotlin/issues/175) for more details. 12 | */ 13 | @Target( 14 | AnnotationTarget.CLASS, 15 | AnnotationTarget.FUNCTION, 16 | AnnotationTarget.PROPERTY, 17 | AnnotationTarget.CONSTRUCTOR, 18 | AnnotationTarget.PROPERTY_GETTER, 19 | AnnotationTarget.PROPERTY_SETTER, 20 | ) 21 | public expect annotation class JsName(val name: String) 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/LineReader.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public interface LineReader { 6 | /** 7 | * Reads and returns the next line, or throws [NoSuchElementException] if no line can be read. 8 | */ 9 | public fun readLine(): String 10 | 11 | /** 12 | * Reads and returns the next line, or returns `null` if no line can be read. 13 | */ 14 | public fun readLineOrNull(): String? 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/StringLineReader.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public class StringLineReader(str: String) : LineReader { 6 | private val lines = str.lineSequence().iterator() 7 | 8 | override fun readLine(): String = 9 | readLineOrNull() ?: throw NoSuchElementException() 10 | 11 | override fun readLineOrNull(): String? = 12 | if (lines.hasNext()) lines.next() else null 13 | } 14 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/Synchronized.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): wait for AtomicFU 0.24.0, so that we can 6 | // integrate it without buildscript hacks. 7 | // Also, how are we going to use the "lock" parameter? 8 | // Probably it makes sense to just tell consumers the 9 | // Kotlin Native implementation is not thread safe. 10 | internal expect inline fun synchronized(lock: Any, block: () -> R): R 11 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal expect class WeakHashMap() : MutableMap { 6 | override val size: Int 7 | override val entries: MutableSet> 8 | override val keys: MutableSet 9 | override val values: MutableCollection 10 | override fun containsKey(key: K): Boolean 11 | override fun containsValue(value: V): Boolean 12 | override fun get(key: K): V? 13 | override fun isEmpty(): Boolean 14 | override fun clear() 15 | override fun put(key: K, value: V): V? 16 | override fun putAll(from: Map) 17 | override fun remove(key: K): V? 18 | } 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/ext/Appendable.ext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime.ext 4 | 5 | import com.strumenta.antlrkotlin.runtime.highSurrogate 6 | import com.strumenta.antlrkotlin.runtime.isBmpCodePoint 7 | import com.strumenta.antlrkotlin.runtime.isValidCodePoint 8 | import com.strumenta.antlrkotlin.runtime.lowSurrogate 9 | 10 | /** 11 | * Appends the string representation of the [codePoint] argument to this sequence. 12 | * 13 | * See Java's `StringBuilder.appendCodePoint`. 14 | */ 15 | public fun T.appendCodePoint(codePoint: Int): T { 16 | if (isBmpCodePoint(codePoint)) { 17 | append(codePoint.toChar()) 18 | } else if (isValidCodePoint(codePoint)) { 19 | append(highSurrogate(codePoint)) 20 | append(lowSurrogate(codePoint)) 21 | } else { 22 | throw IllegalArgumentException("Not a valid Unicode code point: ${codePoint.toHex()}") 23 | } 24 | 25 | return this 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/ext/Array.ext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime.ext 4 | 5 | // See Java's Arrays.binarySearch0 6 | public fun IntArray.binarySearch(element: Int, fromIndex: Int = 0, toIndex: Int = size): Int { 7 | rangeCheck(size, fromIndex, toIndex) 8 | 9 | var low = fromIndex 10 | var high = toIndex - 1 11 | 12 | while (low <= high) { 13 | val mid = (low + high) ushr 1 14 | val midVal = this[mid] 15 | 16 | if (midVal < element) { 17 | low = mid + 1 18 | } else if (midVal > element) { 19 | high = mid - 1 20 | } else { 21 | return mid // key found 22 | } 23 | } 24 | 25 | return -(low + 1) // key not found 26 | } 27 | 28 | private fun rangeCheck(size: Int, fromIndex: Int, toIndex: Int) { 29 | when { 30 | fromIndex > toIndex -> throw IllegalArgumentException("fromIndex($fromIndex) > toIndex($toIndex)") 31 | fromIndex < 0 -> throw IndexOutOfBoundsException("Array index out of range: $fromIndex") 32 | toIndex > size -> throw IndexOutOfBoundsException("Array index out of range: $toIndex") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/ext/Char.ext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime.ext 4 | 5 | import com.strumenta.antlrkotlin.runtime.* 6 | 7 | public fun Char.Companion.isSupplementaryCodePoint(codePoint: Int): Boolean = 8 | codePoint in MIN_SUPPLEMENTARY_CODE_POINT_..MAX_CODE_POINT_ 9 | 10 | public fun Char.Companion.toChars(codePoint: Int, destination: CharArray, offset: Int): Int { 11 | when { 12 | isBmpCodePoint(codePoint) -> { 13 | destination.setSafe(offset, codePoint.toChar()) 14 | return 1 15 | } 16 | isValidCodePoint(codePoint) -> { 17 | // When writing the low surrogate succeeds but writing the high surrogate fails (offset = -1), the 18 | // destination will be modified even though the method throws. This feels wrong, but matches the behavior 19 | // of the Java stdlib implementation. 20 | destination.setSafe(offset + 1, lowSurrogate(codePoint)) 21 | destination.setSafe(offset, highSurrogate(codePoint)) 22 | return 2 23 | } 24 | else -> throw IllegalArgumentException("Not a valid Unicode code point: ${codePoint.toHex()}") 25 | } 26 | } 27 | 28 | public fun Char.Companion.charCount(codePoint: Int): Int = 29 | if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT_) { 30 | 2 31 | } else { 32 | 1 33 | } 34 | 35 | private fun CharArray.setSafe(index: Int, value: Char) { 36 | if (index !in this.indices) { 37 | throw IndexOutOfBoundsException("Size: $size, offset: $index") 38 | } 39 | 40 | this[index] = value 41 | } 42 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/com/strumenta/antlrkotlin/runtime/ext/Int.ext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime.ext 4 | 5 | @OptIn(ExperimentalStdlibApi::class) 6 | private val hexFormat: HexFormat = HexFormat { 7 | upperCase = true 8 | number { 9 | prefix = "0x" 10 | removeLeadingZeros = true 11 | } 12 | } 13 | 14 | @OptIn(ExperimentalStdlibApi::class) 15 | public fun Int.toHex(): String = 16 | toHexString(hexFormat) 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/AbstractCharStreams.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import kotlin.jvm.JvmOverloads 6 | 7 | public abstract class AbstractCharStreams { 8 | /** 9 | * Creates a [CharStream] given a string and the [sourceName] from which it came. 10 | */ 11 | @JvmOverloads 12 | public fun fromString(str: String, sourceName: String = IntStream.UNKNOWN_SOURCE_NAME): CharStream = 13 | StringCharStream(str, sourceName) 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/BaseErrorListener.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import com.strumenta.antlrkotlin.runtime.BitSet 6 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 7 | import org.antlr.v4.kotlinruntime.dfa.DFA 8 | 9 | /** 10 | * Provides an empty default implementation of [ANTLRErrorListener]. 11 | * 12 | * The default implementation of each method does nothing, 13 | * but can be overridden as necessary. 14 | * 15 | * @author Sam Harwell 16 | */ 17 | public open class BaseErrorListener : ANTLRErrorListener { 18 | override fun syntaxError( 19 | recognizer: Recognizer<*, *>, 20 | offendingSymbol: Any?, 21 | line: Int, 22 | charPositionInLine: Int, 23 | msg: String, 24 | e: RecognitionException?, 25 | ) { 26 | // Noop 27 | } 28 | 29 | override fun reportAmbiguity( 30 | recognizer: Parser, 31 | dfa: DFA, 32 | startIndex: Int, 33 | stopIndex: Int, 34 | exact: Boolean, 35 | ambigAlts: BitSet, 36 | configs: ATNConfigSet, 37 | ) { 38 | // Noop 39 | } 40 | 41 | override fun reportAttemptingFullContext( 42 | recognizer: Parser, 43 | dfa: DFA, 44 | startIndex: Int, 45 | stopIndex: Int, 46 | conflictingAlts: BitSet, 47 | configs: ATNConfigSet, 48 | ) { 49 | // Noop 50 | } 51 | 52 | override fun reportContextSensitivity( 53 | recognizer: Parser, 54 | dfa: DFA, 55 | startIndex: Int, 56 | stopIndex: Int, 57 | prediction: Int, 58 | configs: ATNConfigSet, 59 | ) { 60 | // Noop 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/CharStream.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime 5 | 6 | import org.antlr.v4.kotlinruntime.misc.Interval 7 | 8 | /** 9 | * A source of characters for an ANTLR lexer. 10 | */ 11 | public interface CharStream : IntStream { 12 | public companion object { 13 | public const val EOF: Int = IntStream.EOF 14 | } 15 | 16 | /** 17 | * This method returns the text for a range of characters within this input stream. 18 | * 19 | * This method is guaranteed to not throw an exception if the 20 | * specified [interval] lies entirely within a marked range. 21 | * For more information about marked ranges, see [IntStream.mark]. 22 | * 23 | * @param interval An interval within the stream 24 | * @return The text of the specified interval 25 | * 26 | * @throws IllegalArgumentException If `interval.a < 0`, or if 27 | * `interval.b < interval.a - 1`, or if `interval.b` lies at or 28 | * past the end of the stream 29 | * @throws UnsupportedOperationException If the stream does not support 30 | * getting the text of the specified interval 31 | */ 32 | public fun getText(interval: Interval): String 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/ConsoleErrorListener.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import com.strumenta.antlrkotlin.runtime.System 6 | import kotlin.jvm.JvmField 7 | 8 | /** 9 | * @author Sam Harwell 10 | */ 11 | public open class ConsoleErrorListener : BaseErrorListener() { 12 | public companion object { 13 | /** 14 | * Provides a default instance of [ConsoleErrorListener]. 15 | */ 16 | @JvmField 17 | public val INSTANCE: ConsoleErrorListener = ConsoleErrorListener() 18 | } 19 | 20 | /** 21 | * This implementation prints messages to [System.err] containing the 22 | * values of [line], [charPositionInLine], and [msg] using the following format: 23 | * 24 | * ``` 25 | * line *line*:*charPositionInLine* *msg* 26 | * ``` 27 | */ 28 | override fun syntaxError( 29 | recognizer: Recognizer<*, *>, 30 | offendingSymbol: Any?, 31 | line: Int, 32 | charPositionInLine: Int, 33 | msg: String, 34 | e: RecognitionException?, 35 | ) { 36 | System.err.println("line $line:$charPositionInLine $msg") 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/DummyCharStream.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import org.antlr.v4.kotlinruntime.misc.Interval 6 | 7 | /** 8 | * To be used internally instead of a `null` assignment to a [CharStream] property. 9 | * 10 | * @author Edoardo Luppi 11 | */ 12 | internal object DummyCharStream : CharStream { 13 | override val sourceName: String 14 | get() = throw UnsupportedOperationException() 15 | 16 | override fun getText(interval: Interval): String = 17 | throw UnsupportedOperationException() 18 | 19 | override fun consume() = 20 | throw UnsupportedOperationException() 21 | 22 | override fun LA(i: Int): Int = 23 | throw UnsupportedOperationException() 24 | 25 | override fun mark(): Int = 26 | throw UnsupportedOperationException() 27 | 28 | override fun release(marker: Int): Unit = 29 | throw UnsupportedOperationException() 30 | 31 | override fun index(): Int = 32 | throw UnsupportedOperationException() 33 | 34 | override fun seek(index: Int) { 35 | // Noop 36 | } 37 | 38 | override fun size(): Int = 39 | 0 40 | } 41 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/DummyTokenStream.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import org.antlr.v4.kotlinruntime.misc.Interval 6 | 7 | /** 8 | * To be used internally instead of a `null` assignment to a [TokenStream] property. 9 | * 10 | * @author Edoardo Luppi 11 | */ 12 | internal object DummyTokenStream : TokenStream { 13 | override val tokenSource: TokenSource 14 | get() = throw UnsupportedOperationException() 15 | 16 | override val text: String 17 | get() = throw UnsupportedOperationException() 18 | 19 | override val sourceName: String 20 | get() = throw UnsupportedOperationException() 21 | 22 | override fun consume(): Unit = 23 | throw UnsupportedOperationException() 24 | 25 | override fun LA(i: Int): Int = 26 | throw UnsupportedOperationException() 27 | 28 | override fun mark(): Int = 29 | throw UnsupportedOperationException() 30 | 31 | override fun release(marker: Int): Unit = 32 | throw UnsupportedOperationException() 33 | 34 | override fun index(): Int = 35 | throw UnsupportedOperationException() 36 | 37 | override fun seek(index: Int) { 38 | // Noop 39 | } 40 | 41 | override fun size(): Int = 42 | 0 43 | 44 | override fun LT(k: Int): Token = 45 | throw UnsupportedOperationException() 46 | 47 | override fun get(index: Int): Token = 48 | throw UnsupportedOperationException() 49 | 50 | override fun getText(interval: Interval): String = 51 | throw UnsupportedOperationException() 52 | 53 | override fun getText(ctx: RuleContext): String = 54 | throw UnsupportedOperationException() 55 | 56 | override fun getText(start: Token?, stop: Token?): String = 57 | throw UnsupportedOperationException() 58 | } 59 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/EmptyStackException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | /** 6 | * Thrown to indicate that a stack is empty. 7 | */ 8 | public class EmptyStackException(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause) 9 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/FailedPredicateException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import org.antlr.v4.kotlinruntime.atn.AbstractPredicateTransition 6 | import org.antlr.v4.kotlinruntime.atn.PredicateTransition 7 | 8 | /** 9 | * A semantic predicate failed during validation. 10 | * 11 | * Validation of predicates occurs when normally parsing the alternative 12 | * just like matching a token. Disambiguating predicate evaluation occurs 13 | * when we test a predicate during prediction. 14 | */ 15 | @Suppress("MemberVisibilityCanBePrivate") 16 | public class FailedPredicateException( 17 | recognizer: Parser, 18 | public val predicate: String? = null, 19 | message: String? = null, 20 | ) : RecognitionException( 21 | recognizer, 22 | recognizer.tokenStream, 23 | recognizer.context!!, 24 | formatMessage(predicate, message), 25 | ) { 26 | private companion object { 27 | private fun formatMessage(predicate: String?, message: String?): String = 28 | message ?: "failed predicate: {$predicate}?" 29 | } 30 | 31 | public var ruleIndex: Int = -1 32 | public var predIndex: Int = -1 33 | 34 | init { 35 | val s = recognizer.interpreter.atn.states[recognizer.state] 36 | val trans = s!!.transition(0) as AbstractPredicateTransition 37 | 38 | if (trans is PredicateTransition) { 39 | ruleIndex = trans.ruleIndex 40 | predIndex = trans.predIndex 41 | } else { 42 | ruleIndex = 0 43 | predIndex = 0 44 | } 45 | 46 | offendingToken = recognizer.currentToken 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/InputMismatchException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | /** 6 | * This signifies any kind of mismatched input exceptions such as 7 | * when the current input does not match the expected token. 8 | */ 9 | public class InputMismatchException : RecognitionException { 10 | public constructor(recognizer: Parser) : super(recognizer, recognizer.tokenStream, recognizer.context!!) { 11 | offendingToken = recognizer.currentToken 12 | } 13 | 14 | public constructor( 15 | recognizer: Parser, 16 | state: Int, 17 | ctx: ParserRuleContext, 18 | ) : super(recognizer, recognizer.tokenStream, ctx) { 19 | offendingState = state 20 | offendingToken = recognizer.currentToken 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/InterpreterRuleContext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | /** 6 | * This class extends [ParserRuleContext] by allowing the value of 7 | * [ruleIndex] to be explicitly set for the context. 8 | * 9 | * [ParserRuleContext] does not include field storage for the rule index 10 | * since the context classes created by the code generator override the 11 | * [ruleIndex] method to return the correct value for that context. 12 | * 13 | * Since the parser interpreter does not use the context classes generated for a 14 | * parser, this class (with slightly more memory overhead per node) is used to 15 | * provide equivalent functionality. 16 | */ 17 | public class InterpreterRuleContext : ParserRuleContext { 18 | override val ruleIndex: Int 19 | 20 | public constructor() { 21 | ruleIndex = -1 22 | } 23 | 24 | /** 25 | * Constructs a new [InterpreterRuleContext] with the specified 26 | * parent, invoking state, and rule index. 27 | * 28 | * @param parent The parent context 29 | * @param invokingStateNumber The invoking state number 30 | * @param ruleIndex The rule index for the current context 31 | */ 32 | public constructor( 33 | parent: ParserRuleContext?, 34 | invokingStateNumber: Int, 35 | ruleIndex: Int, 36 | ) : super(parent, invokingStateNumber) { 37 | this.ruleIndex = ruleIndex 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/LexerNoViableAltException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime 5 | 6 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 7 | import org.antlr.v4.kotlinruntime.misc.Interval 8 | import org.antlr.v4.kotlinruntime.misc.Utils 9 | 10 | /** 11 | * @param startIndex Matching attempted at what input index? 12 | * @param deadEndConfigs Which configurations did we try at `input.index()` 13 | * that couldn't match `input.LA(1)`? 14 | */ 15 | @Suppress("MemberVisibilityCanBePrivate") 16 | public class LexerNoViableAltException( 17 | lexer: Lexer, 18 | input: CharStream, 19 | public val startIndex: Int, 20 | public val deadEndConfigs: ATNConfigSet?, 21 | ) : RecognitionException(lexer, input, null) { 22 | override val inputStream: CharStream 23 | get() = super.inputStream as CharStream 24 | 25 | override fun toString(): String { 26 | var symbol = "" 27 | 28 | if (startIndex >= 0 && startIndex < inputStream.size()) { 29 | symbol = inputStream.getText(Interval.of(startIndex, startIndex)) 30 | symbol = Utils.escapeWhitespace(symbol, false) 31 | } 32 | 33 | return "${this::class.simpleName}('$symbol')" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/NoViableAltException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet 6 | 7 | /** 8 | * Indicates that the parser could not decide which of two or more paths 9 | * to take based upon the remaining input. 10 | * 11 | * It tracks the starting token of the offending input and also knows where 12 | * the parser was in the various paths when the error. 13 | * 14 | * Reported by `reportNoViableAlternative()`. 15 | * 16 | * @param startToken The token object at the start index; the input stream might 17 | * not be buffering tokens so get a reference to it. (At the 18 | * time the error occurred, of course the stream needs to keep a 19 | * buffer all the tokens, but later we might not have access to those) 20 | * @param deadEndConfigs Which configurations did we try at `input.index()` 21 | * that couldn't match `input.LT(1)`? 22 | */ 23 | public class NoViableAltException( 24 | recognizer: Parser, 25 | input: TokenStream = recognizer.tokenStream, 26 | public val startToken: Token? = recognizer.currentToken, 27 | offendingToken: Token? = recognizer.currentToken, 28 | public val deadEndConfigs: ATNConfigSet? = null, 29 | ctx: ParserRuleContext = recognizer.context!!, 30 | ) : RecognitionException(recognizer, input, ctx) { 31 | init { 32 | this.offendingToken = offendingToken 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/RuleContextWithAltNum.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime 5 | 6 | import org.antlr.v4.kotlinruntime.atn.ATN 7 | 8 | /** 9 | * A handy class for use with 10 | * 11 | * ``` 12 | * options { 13 | * contextSuperClass = org.antlr.v4.runtime.RuleContextWithAltNum; 14 | * } 15 | * ``` 16 | * 17 | * that provides a backing field/impl for the outer alternative number 18 | * matched for an internal parse tree node. 19 | * 20 | * I'm only putting into Java runtime as I'm certain I'm the only one that 21 | * will really every use this. 22 | */ 23 | public class RuleContextWithAltNum : ParserRuleContext { 24 | override var altNumber: Int = 0 25 | 26 | public constructor() { 27 | altNumber = ATN.INVALID_ALT_NUMBER 28 | } 29 | 30 | public constructor(parent: ParserRuleContext, invokingStateNumber: Int) : super(parent, invokingStateNumber) 31 | } 32 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/TokenFactory.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime 5 | 6 | /** 7 | * The default mechanism for creating tokens. It's used by default in [Lexer] and 8 | * the error handling strategy (to create missing tokens). Notifying the [Parser] 9 | * of a new factory means that it notifies its token source and error strategy. 10 | */ 11 | public interface TokenFactory { 12 | /** 13 | * This is the method used to create tokens in the lexer and in the 14 | * error handling strategy. If `text != null`, than the start and stop positions 15 | * are wiped to `-1` in the text override is set in the [CommonToken]. 16 | */ 17 | public fun create( 18 | source: Pair, 19 | type: Int, 20 | text: String?, 21 | channel: Int, 22 | start: Int, 23 | stop: Int, 24 | line: Int, 25 | charPositionInLine: Int, 26 | ): Symbol 27 | 28 | /** 29 | * Generically useful. 30 | */ 31 | public fun create(type: Int, text: String): Symbol 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/WritableToken.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime 5 | 6 | public interface WritableToken : Token { 7 | override var text: String? 8 | 9 | /** 10 | * Get the token type of the token. 11 | */ 12 | override var type: Int 13 | 14 | /** 15 | * The line number on which the 1st character of this token was matched, 16 | * `line=1..n`. 17 | */ 18 | override var line: Int 19 | 20 | /** 21 | * The index of the first character of this token relative to the 22 | * beginning of the line at which it occurs, `0..n-1`. 23 | */ 24 | override var charPositionInLine: Int 25 | 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 | * 30 | * The parser ignores everything not on [Token.DEFAULT_CHANNEL]. 31 | */ 32 | override var channel: Int 33 | 34 | /** 35 | * An index from `0..n-1` of the token object in the input stream. 36 | * This must be valid in order to print token streams and 37 | * use `TokenRewriteStream`. 38 | * 39 | * Return `-1` to indicate that this token was conjured up since 40 | * it doesn't have a valid index. 41 | */ 42 | override var tokenIndex: Int 43 | } 44 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/ast/Node.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.ast 4 | 5 | /** 6 | * The Abstract Syntax Tree will be constituted by instances of [Node]. 7 | */ 8 | public interface Node { 9 | public val parent: Node? 10 | public val position: Position? 11 | } 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/ast/Position.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.ast 4 | 5 | /** 6 | * Both the [start] point and the [end] point are inclusive. 7 | */ 8 | public data class Position(val start: Point, val end: Point) { 9 | public constructor( 10 | startLine: Int, 11 | startCol: Int, 12 | endLine: Int, 13 | endCol: Int, 14 | ) : this(Point(startLine, startCol), Point(endLine, endCol)) 15 | 16 | init { 17 | require(start.isBefore(end) || start == end) { 18 | "End should follows start or be the same as start (start: $start, end: $end)" 19 | } 20 | } 21 | 22 | /** 23 | * Given the whole code, extract the portion of text corresponding to this position. 24 | */ 25 | public fun text(wholeText: String): String = 26 | wholeText.substring(start.offset(wholeText), end.offset(wholeText)) 27 | 28 | public fun length(code: String): Int = 29 | end.offset(code) - start.offset(code) 30 | 31 | public fun contains(point: Point): Boolean = 32 | ((point == start || start.isBefore(point)) && (point == end || point.isBefore(end))) 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/ATNDeserializationOptions.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | import kotlin.jvm.JvmField 6 | 7 | /** 8 | * @author Sam Harwell 9 | */ 10 | public open class ATNDeserializationOptions { 11 | public companion object { 12 | @JvmField 13 | public val defaultOptions: ATNDeserializationOptions = ATNDeserializationOptions().also { 14 | it.makeReadOnly() 15 | } 16 | } 17 | 18 | private var readOnly = false 19 | private var verifyATN = false 20 | private var generateRuleBypassTransitions = false 21 | 22 | @Suppress("MemberVisibilityCanBePrivate") 23 | public open val isReadOnly: Boolean 24 | get() = readOnly 25 | 26 | public open var isVerifyATN: Boolean 27 | get() = verifyATN 28 | set(value) { 29 | throwIfReadOnly() 30 | verifyATN = value 31 | } 32 | 33 | public open var isGenerateRuleBypassTransitions: Boolean 34 | get() = generateRuleBypassTransitions 35 | set(value) { 36 | throwIfReadOnly() 37 | generateRuleBypassTransitions = value 38 | } 39 | 40 | public constructor() { 41 | verifyATN = true 42 | generateRuleBypassTransitions = false 43 | } 44 | 45 | public constructor(options: ATNDeserializationOptions) { 46 | verifyATN = options.verifyATN 47 | generateRuleBypassTransitions = options.generateRuleBypassTransitions 48 | } 49 | 50 | public open fun makeReadOnly() { 51 | readOnly = true 52 | } 53 | 54 | protected open fun throwIfReadOnly() { 55 | if (readOnly) { 56 | throw IllegalStateException("The object is read only.") 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/ATNType.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Represents the type of recognizer an ATN applies to. 8 | * 9 | * @author Sam Harwell 10 | */ 11 | public enum class ATNType { 12 | /** 13 | * A lexer grammar. 14 | */ 15 | LEXER, 16 | 17 | /** 18 | * A parser grammar. 19 | */ 20 | PARSER, 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/AbstractPredicateTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * @author Sam Harwell 8 | */ 9 | public abstract class AbstractPredicateTransition(target: ATNState) : Transition(target) 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/ActionTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public class ActionTransition( 7 | target: ATNState, 8 | public val ruleIndex: Int, 9 | public val actionIndex: Int = -1, 10 | public val isCtxDependent: Boolean = false, // e.g., $i ref in action 11 | ) : Transition(target) { 12 | override val serializationType: Int = 13 | ACTION 14 | 15 | override val isEpsilon: Boolean = 16 | true 17 | 18 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 19 | false 20 | 21 | override fun toString(): String = 22 | "action_$ruleIndex:$actionIndex" 23 | } 24 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/AtomTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 7 | 8 | /** 9 | * TODO: make all transitions sets? No, should remove set edges. 10 | * 11 | * @param label The token type or character value. Or, signifies special label 12 | */ 13 | public class AtomTransition(target: ATNState, public val label: Int) : Transition(target) { 14 | override val serializationType: Int = 15 | ATOM 16 | 17 | override fun label(): IntervalSet = 18 | IntervalSet.of(label) 19 | 20 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 21 | label == symbol 22 | 23 | override fun toString(): String = 24 | label.toString() 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/BasicBlockStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * @author Sam Harwell 8 | */ 9 | public class BasicBlockStartState : BlockStartState() { 10 | override val stateType: Int = 11 | BLOCK_START 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/BasicState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * @author Sam Harwell 8 | */ 9 | public class BasicState : ATNState() { 10 | override val stateType: Int = 11 | BASIC 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/BlockEndState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Terminal node of a simple `(a|b|c)` block. 8 | */ 9 | public class BlockEndState : ATNState() { 10 | public var startState: BlockStartState? = null 11 | 12 | override val stateType: Int = 13 | BLOCK_END 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/BlockStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * The start of a regular `(...)` block. 8 | */ 9 | public abstract class BlockStartState : DecisionState() { 10 | public var endState: BlockEndState? = null 11 | } 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/CodePointTransitions.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Utility class to create [AtomTransition], [RangeTransition], 8 | * and [SetTransition] appropriately based on the range of the input. 9 | * 10 | * Previously, we distinguished between atom and range transitions for 11 | * Unicode code points <= `U+FFFF` and those above. We used a set 12 | * transition for a Unicode code point > `U+FFFF`. Now that we can serialize 13 | * 32-bit int/chars in the ATN serialization, this is no longer necessary. 14 | */ 15 | @Suppress("MemberVisibilityCanBePrivate") 16 | public object CodePointTransitions { 17 | /** 18 | * Return new [AtomTransition]. 19 | */ 20 | public fun createWithCodePoint(target: ATNState, codePoint: Int): Transition = 21 | createWithCodePointRange(target, codePoint, codePoint) 22 | 23 | /** 24 | * Return new [AtomTransition] if range represents one atom, else [SetTransition]. 25 | */ 26 | public fun createWithCodePointRange(target: ATNState, codePointFrom: Int, codePointTo: Int): Transition = 27 | if (codePointFrom == codePointTo) { 28 | AtomTransition(target, codePointFrom) 29 | } else { 30 | RangeTransition(target, codePointFrom, codePointTo) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/ContextSensitivityInfo.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.ANTLRErrorListener 7 | import org.antlr.v4.kotlinruntime.TokenStream 8 | 9 | /** 10 | * This class represents profiling event information for a context sensitivity. 11 | * Context sensitivities are decisions where a particular input resulted in an 12 | * SLL conflict, but LL prediction produced a single unique alternative. 13 | * 14 | * In some cases, the unique alternative identified by LL prediction is not 15 | * equal to the minimum represented alternative in the conflicting SLL 16 | * configuration set. Grammars and inputs which result in this scenario are 17 | * unable to use [PredictionMode.SLL], which in turn means they cannot use 18 | * the two-stage parsing strategy to improve parsing performance for that 19 | * input. 20 | * 21 | * @param decision The decision number 22 | * @param configs The final configuration set containing the unique 23 | * alternative identified by full-context prediction 24 | * @param input The input token stream 25 | * @param startIndex The start index for the current prediction 26 | * @param stopIndex The index at which the context sensitivity was 27 | * identified during full-context prediction 28 | * 29 | * @see ParserATNSimulator.reportContextSensitivity 30 | * @see ANTLRErrorListener.reportContextSensitivity 31 | * 32 | * @since 4.3 33 | */ 34 | public class ContextSensitivityInfo( 35 | decision: Int, 36 | configs: ATNConfigSet?, 37 | input: TokenStream, 38 | startIndex: Int, 39 | stopIndex: Int, 40 | ) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, true) 41 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/DecisionState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public abstract class DecisionState : ATNState() { 7 | public var decision: Int = -1 8 | public var nonGreedy: Boolean = false 9 | } 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/EmptyPredictionContext.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | public object EmptyPredictionContext : SingletonPredictionContext(null, EMPTY_RETURN_STATE) { 6 | override val isEmpty: Boolean = 7 | true 8 | 9 | override fun size(): Int = 10 | 1 11 | 12 | override fun getParent(index: Int): PredictionContext? = 13 | null 14 | 15 | override fun getReturnState(index: Int): Int { 16 | // Note: it was 'return returnState' 17 | // Changed because of https://youtrack.jetbrains.com/issue/KT-22161 18 | // Do not change back! 19 | return EMPTY_RETURN_STATE 20 | } 21 | 22 | override fun equals(other: Any?): Boolean = 23 | this === other 24 | 25 | override fun toString(): String = 26 | "$" 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/EpsilonTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public class EpsilonTransition(target: ATNState, outermostPrecedenceReturn: Int = -1) : Transition(target) { 7 | override val serializationType: Int = 8 | EPSILON 9 | 10 | override val isEpsilon: Boolean = 11 | true 12 | 13 | /** 14 | * The rule index of a precedence rule for which this transition is 15 | * returning from, where the precedence value is `0`, otherwise `-1`. 16 | * 17 | * @see ATNConfig.isPrecedenceFilterSuppressed 18 | * @see ParserATNSimulator.applyPrecedenceFilter 19 | * 20 | * @since 4.4.1 21 | */ 22 | @Suppress("CanBePrimaryConstructorProperty") 23 | public val outermostPrecedenceReturn: Int = 24 | outermostPrecedenceReturn 25 | 26 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 27 | false 28 | 29 | override fun toString(): String = 30 | "epsilon" 31 | } 32 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/ErrorInfo.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.ANTLRErrorListener 7 | import org.antlr.v4.kotlinruntime.Parser 8 | import org.antlr.v4.kotlinruntime.TokenStream 9 | 10 | /** 11 | * This class represents profiling event information for a syntax error 12 | * identified during prediction. 13 | * 14 | * Syntax errors occur when the prediction algorithm is unable to identify 15 | * an alternative which would lead to a successful parse. 16 | * 17 | * @param decision The decision number 18 | * @param configs The final configuration set reached during prediction 19 | * prior to reaching the [ATNSimulator.ERROR] state 20 | * @param input The input token stream 21 | * @param startIndex The start index for the current prediction 22 | * @param stopIndex The index at which the syntax error was identified 23 | * @param fullCtx `true` if the syntax error was identified during LL 24 | * prediction, otherwise `false` if the syntax error was identified 25 | * during SLL prediction 26 | * 27 | * @see Parser.notifyErrorListeners 28 | * @see ANTLRErrorListener.syntaxError 29 | * 30 | * @since 4.3 31 | */ 32 | public class ErrorInfo( 33 | decision: Int, 34 | configs: ATNConfigSet?, 35 | input: TokenStream, 36 | startIndex: Int, 37 | stopIndex: Int, 38 | fullCtx: Boolean, 39 | ) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) 40 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.CharStream 7 | import org.antlr.v4.kotlinruntime.Lexer 8 | 9 | /** 10 | * Represents a single action which can be executed following the successful 11 | * match of a lexer rule. 12 | * 13 | * Lexer actions are used for both embedded action syntax 14 | * and ANTLR 4's new lexer command syntax. 15 | * 16 | * @author Sam Harwell 17 | * @since 4.2 18 | */ 19 | public interface LexerAction { 20 | /** 21 | * The serialization type of the lexer action. 22 | */ 23 | public val actionType: LexerActionType 24 | 25 | /** 26 | * Whether the lexer action is position-dependent. 27 | * 28 | * Position-dependent actions may have different semantics depending 29 | * on the [CharStream] index at the time the action is executed. 30 | * 31 | * Many lexer commands, including `type`, `skip`, and `more`, 32 | * do not check the input index during their execution. 33 | * 34 | * Actions like this are position-independent, and may be stored more 35 | * efficiently as part of the [LexerATNConfig.lexerActionExecutor]. 36 | * 37 | * @return `true` if the lexer action semantics can be affected by the 38 | * position of the input [CharStream] at the time it is executed, 39 | * otherwise `false` 40 | */ 41 | public val isPositionDependent: Boolean 42 | 43 | /** 44 | * Execute the lexer action in the context of the specified [Lexer]. 45 | * 46 | * For position-dependent actions, the input stream must already be 47 | * positioned correctly prior to calling this method. 48 | * 49 | * @param lexer The lexer instance 50 | */ 51 | public fun execute(lexer: Lexer) 52 | } 53 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerActionType.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Represents the serialization type of a [LexerAction]. 8 | * 9 | * @author Sam Harwell 10 | * @since 4.2 11 | */ 12 | public enum class LexerActionType { 13 | /** 14 | * The type of a [LexerChannelAction] action. 15 | */ 16 | CHANNEL, 17 | 18 | /** 19 | * The type of a [LexerCustomAction] action. 20 | */ 21 | CUSTOM, 22 | 23 | /** 24 | * The type of a [LexerModeAction] action. 25 | */ 26 | MODE, 27 | 28 | /** 29 | * The type of a [LexerMoreAction] action. 30 | */ 31 | MORE, 32 | 33 | /** 34 | * The type of a [LexerPopModeAction] action. 35 | */ 36 | POP_MODE, 37 | 38 | /** 39 | * The type of a [LexerPushModeAction] action. 40 | */ 41 | PUSH_MODE, 42 | 43 | /** 44 | * The type of a [LexerSkipAction] action. 45 | */ 46 | SKIP, 47 | 48 | /** 49 | * The type of a [LexerTypeAction] action. 50 | */ 51 | TYPE, 52 | } 53 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerChannelAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.Lexer 7 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 8 | 9 | /** 10 | * Implements the `channel` lexer action by setting [Lexer.channel] 11 | * with the assigned channel. 12 | * 13 | * @param channel The channel value to assign to [Lexer.channel] 14 | * 15 | * @author Sam Harwell 16 | * @since 4.2 17 | */ 18 | public class LexerChannelAction(public val channel: Int) : LexerAction { 19 | /** 20 | * Set to [LexerActionType.CHANNEL] by default. 21 | */ 22 | override val actionType: LexerActionType = 23 | LexerActionType.CHANNEL 24 | 25 | /** 26 | * Set to `false` by default. 27 | */ 28 | override val isPositionDependent: Boolean = 29 | false 30 | 31 | /** 32 | * This action is implemented by assigning [Lexer.channel] with the 33 | * value provided by [channel]. 34 | */ 35 | override fun execute(lexer: Lexer) { 36 | lexer.channel = channel 37 | } 38 | 39 | override fun hashCode(): Int { 40 | var hash = MurmurHash.initialize() 41 | hash = MurmurHash.update(hash, actionType.ordinal) 42 | hash = MurmurHash.update(hash, channel) 43 | return MurmurHash.finish(hash, 2) 44 | } 45 | 46 | override fun equals(other: Any?): Boolean { 47 | if (other === this) { 48 | return true 49 | } 50 | 51 | if (other !is LexerChannelAction) { 52 | return false 53 | } 54 | 55 | return channel == other.channel 56 | } 57 | 58 | override fun toString(): String = 59 | "channel($channel)" 60 | } 61 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerModeAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.Lexer 7 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 8 | 9 | /** 10 | * Implements the `mode` lexer action by calling [Lexer.mode] with 11 | * the assigned mode. 12 | * 13 | * @param mode The mode value to pass to [Lexer.mode] 14 | * 15 | * @author Sam Harwell 16 | * @since 4.2 17 | */ 18 | public class LexerModeAction(public val mode: Int) : LexerAction { 19 | /** 20 | * Returns [LexerActionType.MODE]. 21 | */ 22 | override val actionType: LexerActionType = 23 | LexerActionType.MODE 24 | 25 | /** 26 | * Returns `false`. 27 | */ 28 | override val isPositionDependent: Boolean = 29 | false 30 | 31 | /** 32 | * This action is implemented by calling [Lexer.mode] with [mode]. 33 | */ 34 | override fun execute(lexer: Lexer): Unit = 35 | lexer.mode(mode) 36 | 37 | override fun hashCode(): Int { 38 | var hash = MurmurHash.initialize() 39 | hash = MurmurHash.update(hash, actionType.ordinal) 40 | hash = MurmurHash.update(hash, mode) 41 | return MurmurHash.finish(hash, 2) 42 | } 43 | 44 | override fun equals(other: Any?): Boolean { 45 | if (other === this) { 46 | return true 47 | } 48 | 49 | if (other !is LexerModeAction) { 50 | return false 51 | } 52 | 53 | return mode == other.mode 54 | } 55 | 56 | override fun toString(): String = 57 | "mode($mode)" 58 | } 59 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerMoreAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | import org.antlr.v4.kotlinruntime.Lexer 6 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 7 | 8 | /** 9 | * Implements the `more` lexer action by calling [Lexer.more]. 10 | * 11 | * The `more` command does not have any parameters, 12 | * so this action is implemented as an object. 13 | * 14 | * @author Sam Harwell 15 | * @since 4.2 16 | */ 17 | public object LexerMoreAction : LexerAction { 18 | /** 19 | * Returns [LexerActionType.MORE]. 20 | */ 21 | override val actionType: LexerActionType = 22 | LexerActionType.MORE 23 | 24 | /** 25 | * Returns `false`. 26 | */ 27 | override val isPositionDependent: Boolean = 28 | false 29 | 30 | /** 31 | * This action is implemented by calling [Lexer.more]. 32 | */ 33 | override fun execute(lexer: Lexer): Unit = 34 | lexer.more() 35 | 36 | override fun hashCode(): Int { 37 | var hash = MurmurHash.initialize() 38 | hash = MurmurHash.update(hash, actionType.ordinal) 39 | return MurmurHash.finish(hash, 1) 40 | } 41 | 42 | override fun equals(other: Any?): Boolean = 43 | other === this 44 | 45 | override fun toString(): String = 46 | "more" 47 | } 48 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPopModeAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | import org.antlr.v4.kotlinruntime.Lexer 6 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 7 | 8 | /** 9 | * Implements the `popMode` lexer action by calling [Lexer.popMode]. 10 | * 11 | * The `popMode` command does not have any parameters, 12 | * so this action is implemented as an object. 13 | * 14 | * @author Sam Harwell 15 | * @since 4.2 16 | */ 17 | public object LexerPopModeAction : LexerAction { 18 | /** 19 | * Returns [LexerActionType.POP_MODE]. 20 | */ 21 | override val actionType: LexerActionType = 22 | LexerActionType.POP_MODE 23 | 24 | /** 25 | * Returns `false`. 26 | */ 27 | override val isPositionDependent: Boolean = 28 | false 29 | 30 | /** 31 | * This action is implemented by calling [Lexer.popMode]. 32 | */ 33 | override fun execute(lexer: Lexer) { 34 | lexer.popMode() 35 | } 36 | 37 | override fun hashCode(): Int { 38 | var hash = MurmurHash.initialize() 39 | hash = MurmurHash.update(hash, actionType.ordinal) 40 | return MurmurHash.finish(hash, 1) 41 | } 42 | 43 | override fun equals(other: Any?): Boolean = 44 | other === this 45 | 46 | override fun toString(): String = 47 | "popMode" 48 | } 49 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPushModeAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.Lexer 7 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 8 | 9 | /** 10 | * Implements the `pushMode` lexer action by calling 11 | * [Lexer.pushMode] with the assigned mode. 12 | * 13 | * @param mode The mode value to pass to [Lexer.pushMode] 14 | * 15 | * @author Sam Harwell 16 | * @since 4.2 17 | */ 18 | public class LexerPushModeAction(public val mode: Int) : LexerAction { 19 | /** 20 | * Returns [LexerActionType.PUSH_MODE]. 21 | */ 22 | override val actionType: LexerActionType = 23 | LexerActionType.PUSH_MODE 24 | 25 | /** 26 | * Returns `false`. 27 | */ 28 | override val isPositionDependent: Boolean = 29 | false 30 | 31 | /** 32 | * This action is implemented by calling [Lexer.pushMode] with [mode]. 33 | */ 34 | override fun execute(lexer: Lexer): Unit = 35 | lexer.pushMode(mode) 36 | 37 | override fun hashCode(): Int { 38 | var hash = MurmurHash.initialize() 39 | hash = MurmurHash.update(hash, actionType.ordinal) 40 | hash = MurmurHash.update(hash, mode) 41 | return MurmurHash.finish(hash, 2) 42 | } 43 | 44 | override fun equals(other: Any?): Boolean { 45 | if (other === this) { 46 | return true 47 | } 48 | 49 | if (other !is LexerPushModeAction) { 50 | return false 51 | } 52 | 53 | return mode == other.mode 54 | } 55 | 56 | override fun toString(): String = 57 | "pushMode($mode)" 58 | } 59 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerSkipAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | import org.antlr.v4.kotlinruntime.Lexer 6 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 7 | 8 | /** 9 | * Implements the `skip` lexer action by calling [Lexer.skip]. 10 | * 11 | * The `skip` command does not have any parameters, 12 | * so this action is implemented as an object. 13 | * 14 | * @author Sam Harwell 15 | * @since 4.2 16 | */ 17 | public object LexerSkipAction : LexerAction { 18 | /** 19 | * Returns [LexerActionType.SKIP]. 20 | */ 21 | override val actionType: LexerActionType = 22 | LexerActionType.SKIP 23 | 24 | /** 25 | * Returns `false`. 26 | */ 27 | override val isPositionDependent: Boolean = 28 | false 29 | 30 | /** 31 | * This action is implemented by calling [Lexer.skip]. 32 | */ 33 | override fun execute(lexer: Lexer): Unit = 34 | lexer.skip() 35 | 36 | override fun hashCode(): Int { 37 | var hash = MurmurHash.initialize() 38 | hash = MurmurHash.update(hash, actionType.ordinal) 39 | return MurmurHash.finish(hash, 1) 40 | } 41 | 42 | override fun equals(other: Any?): Boolean = 43 | other === this 44 | 45 | override fun toString(): String = 46 | "skip" 47 | } 48 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LexerTypeAction.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.Lexer 7 | import org.antlr.v4.kotlinruntime.misc.MurmurHash 8 | 9 | /** 10 | * Implements the `type` lexer action by setting [Lexer.type] 11 | * to the assigned type. 12 | * 13 | * @param type The type to assign to the token using [Lexer.type] 14 | * 15 | * @author Sam Harwell 16 | * @since 4.2 17 | */ 18 | public class LexerTypeAction(public val type: Int) : LexerAction { 19 | /** 20 | * Returns [LexerActionType.TYPE]. 21 | */ 22 | override val actionType: LexerActionType = 23 | LexerActionType.TYPE 24 | 25 | /** 26 | * Returns `false`. 27 | */ 28 | override val isPositionDependent: Boolean = 29 | false 30 | 31 | /** 32 | * This action is implemented by assigning [Lexer.type] the 33 | * value provided by [type]. 34 | */ 35 | override fun execute(lexer: Lexer) { 36 | lexer.type = type 37 | } 38 | 39 | override fun hashCode(): Int { 40 | var hash = MurmurHash.initialize() 41 | hash = MurmurHash.update(hash, actionType.ordinal) 42 | hash = MurmurHash.update(hash, type) 43 | return MurmurHash.finish(hash, 2) 44 | } 45 | 46 | override fun equals(other: Any?): Boolean { 47 | if (other === this) { 48 | return true 49 | } 50 | 51 | if (other !is LexerTypeAction) { 52 | return false 53 | } 54 | 55 | return type == other.type 56 | } 57 | 58 | override fun toString(): String = 59 | "type($type)" 60 | } 61 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LookaheadEventInfo.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.TokenStream 7 | 8 | /** 9 | * This class represents profiling event information for tracking the lookahead 10 | * depth required in order to make a prediction. 11 | * 12 | * @param decision The decision number 13 | * @param configs The final configuration set containing the necessary 14 | * information to determine the result of a prediction, or `null` if 15 | * the final configuration set is not available 16 | * @param predictedAlt The alternative chosen by `adaptivePredict()`, 17 | * not necessarily the outermost alt shown for a rule. 18 | * Left-recursive rules have user-level alts that differ from 19 | * the rewritten rule with a `(...)` block and a `(..)*` loop 20 | * @param input The input token stream 21 | * @param startIndex The start index for the current prediction 22 | * @param stopIndex The index at which the prediction was finally made 23 | * @param fullCtx `true` if the current lookahead is part of an LL 24 | * prediction, otherwise `false` if the current lookahead is part of 25 | * an SLL prediction 26 | * 27 | * @since 4.3 28 | */ 29 | @Suppress("MemberVisibilityCanBePrivate") 30 | public class LookaheadEventInfo( 31 | decision: Int, 32 | configs: ATNConfigSet?, 33 | public var predictedAlt: Int, 34 | input: TokenStream, 35 | startIndex: Int, 36 | stopIndex: Int, 37 | fullCtx: Boolean, 38 | ) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) 39 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/LoopEndState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Mark the end of a * or + loop. 8 | */ 9 | public class LoopEndState : ATNState() { 10 | public var loopBackState: ATNState? = null 11 | 12 | override val stateType: Int = 13 | LOOP_END 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/NotSetTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 7 | 8 | public class NotSetTransition(target: ATNState, set: IntervalSet) : SetTransition(target, set) { 9 | override val serializationType: Int = 10 | NOT_SET 11 | 12 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 13 | symbol in minVocabSymbol..maxVocabSymbol && !super.matches(symbol, minVocabSymbol, maxVocabSymbol) 14 | 15 | override fun toString(): String = 16 | "~${super.toString()}" 17 | } 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/OrderedATNConfigSet.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.atn 4 | 5 | import org.antlr.v4.kotlinruntime.misc.ObjectEqualityComparator 6 | 7 | /** 8 | * @author Sam Harwell 9 | */ 10 | public class OrderedATNConfigSet : ATNConfigSet() { 11 | public class LexerConfigHashSet : AbstractConfigHashSet(ObjectEqualityComparator.INSTANCE) 12 | 13 | init { 14 | configLookup = LexerConfigHashSet() 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/PlusBlockStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Start of `(A|B|...)+` loop. 8 | * 9 | * Technically a decision state, but we don't use for code generation. 10 | * Somebody might need it, so I'm defining it for completeness. 11 | * 12 | * In reality, the [PlusLoopbackState] node is the real decision-making note for `A+`. 13 | */ 14 | public class PlusBlockStartState : BlockStartState() { 15 | public var loopBackState: PlusLoopbackState? = null 16 | 17 | override val stateType: Int = 18 | PLUS_BLOCK_START 19 | } 20 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/PlusLoopbackState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Decision state for `A+` and `(A|B)+`. 8 | * 9 | * It has two transitions: one to the loop back to start of the block and one to exit. 10 | */ 11 | public class PlusLoopbackState : DecisionState() { 12 | override val stateType: Int = 13 | PLUS_LOOP_BACK 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/PrecedencePredicateTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * @author Sam Harwell 8 | */ 9 | public class PrecedencePredicateTransition( 10 | target: ATNState, 11 | public val precedence: Int, 12 | ) : AbstractPredicateTransition(target) { 13 | 14 | override val serializationType: Int = 15 | PRECEDENCE 16 | 17 | override val isEpsilon: Boolean = 18 | true 19 | 20 | public val predicate: SemanticContext.PrecedencePredicate 21 | get() = SemanticContext.PrecedencePredicate(precedence) 22 | 23 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 24 | false 25 | 26 | override fun toString(): String = 27 | "$precedence >= _p" 28 | } 29 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/PredicateTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * TODO: this is old comment 8 | * 9 | * A tree of semantic predicates from the grammar AST if `label == SEMPRED`. 10 | * 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 | public class PredicateTransition( 16 | target: ATNState, 17 | public val ruleIndex: Int, 18 | public val predIndex: Int, 19 | public val isCtxDependent: Boolean, // e.g., $i ref in pred 20 | ) : AbstractPredicateTransition(target) { 21 | override val serializationType: Int = 22 | PREDICATE 23 | 24 | override val isEpsilon: Boolean = 25 | true 26 | 27 | public val predicate: SemanticContext.Predicate 28 | get() = SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent) 29 | 30 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 31 | false 32 | 33 | override fun toString(): String = 34 | "pred_$ruleIndex:$predIndex" 35 | } 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/PredictionContextCache.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * Used to cache [PredictionContext] objects. 8 | * 9 | * It's used for the shared context cash associated with contexts in DFA states. 10 | * 11 | * This cache can be used for both lexers and parsers. 12 | */ 13 | public open class PredictionContextCache { 14 | protected val cache: MutableMap = HashMap() 15 | 16 | /** 17 | * Add a context to the cache and return it. 18 | * 19 | * If the context already exists, return that one instead and 20 | * do not add a new context to the cache. 21 | * 22 | * Protect shared cache from unsafe thread access. 23 | */ 24 | public open fun add(ctx: PredictionContext): PredictionContext { 25 | if (ctx === EmptyPredictionContext) { 26 | return EmptyPredictionContext 27 | } 28 | 29 | val existing = cache[ctx] 30 | 31 | if (existing != null) { 32 | return existing 33 | } 34 | 35 | cache[ctx] = ctx 36 | return ctx 37 | } 38 | 39 | public open operator fun get(ctx: PredictionContext): PredictionContext? = 40 | cache[ctx] 41 | 42 | public open fun size(): Int = 43 | cache.size 44 | } 45 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/RangeTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import com.strumenta.antlrkotlin.runtime.ext.appendCodePoint 7 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 8 | 9 | public class RangeTransition(target: ATNState, public val from: Int, public val to: Int) : Transition(target) { 10 | override val serializationType: Int = 11 | RANGE 12 | 13 | override fun label(): IntervalSet = 14 | IntervalSet.of(from, to) 15 | 16 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 17 | symbol in from..to 18 | 19 | override fun toString(): String { 20 | val buf = StringBuilder("'") 21 | buf.appendCodePoint(from) 22 | buf.append("'..'") 23 | buf.appendCodePoint(to) 24 | buf.append("'") 25 | return buf.toString() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public class RuleStartState : ATNState() { 7 | public var stopState: RuleStopState? = null 8 | public var isLeftRecursiveRule: Boolean = false 9 | 10 | override val stateType: Int = 11 | RULE_START 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStopState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * The last node in the ATN for a rule, unless that rule is the start symbol. 8 | * 9 | * In that case, there is one transition to `EOF`. Later, we might encode 10 | * references to all calls to this rule to compute `FOLLOW` sets for 11 | * error handling. 12 | */ 13 | public class RuleStopState : ATNState() { 14 | override val stateType: Int = 15 | RULE_STOP 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/RuleTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * @param ruleIndex Ptr to the rule definition object for this rule rer 8 | * @param followState What node to begin computations following ref to rule 9 | */ 10 | public class RuleTransition( 11 | ruleStart: RuleStartState, 12 | public val ruleIndex: Int, 13 | public val precedence: Int, 14 | public var followState: ATNState, 15 | ) : Transition(ruleStart) { 16 | override val serializationType: Int = 17 | RULE 18 | 19 | override val isEpsilon: Boolean = 20 | true 21 | 22 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 23 | false 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/SetTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.Token 7 | import org.antlr.v4.kotlinruntime.misc.IntervalSet 8 | 9 | /** 10 | * A transition containing a set of values. 11 | * 12 | * TODO(sam): should we really allow null here? 13 | */ 14 | public open class SetTransition(target: ATNState, set: IntervalSet?) : Transition(target) { 15 | public val set: IntervalSet = set ?: IntervalSet.of(Token.INVALID_TYPE) 16 | 17 | override val serializationType: Int = 18 | SET 19 | 20 | override fun label(): IntervalSet = 21 | set 22 | 23 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 24 | set.contains(symbol) 25 | 26 | override fun toString(): String = 27 | set.toString() 28 | } 29 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/StarBlockStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * The block that begins a closure loop. 8 | */ 9 | public class StarBlockStartState : BlockStartState() { 10 | override val stateType: Int = 11 | STAR_BLOCK_START 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopEntryState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | import org.antlr.v4.kotlinruntime.ParserInterpreter 7 | import org.antlr.v4.kotlinruntime.dfa.DFA 8 | 9 | public class StarLoopEntryState : DecisionState() { 10 | public var loopBackState: StarLoopbackState? = null 11 | 12 | /** 13 | * Indicates whether this state can benefit from a precedence DFA during SLL 14 | * decision-making. 15 | * 16 | * This is a computed property that is calculated during ATN deserialization 17 | * and stored for use in [ParserATNSimulator] and [ParserInterpreter]. 18 | * 19 | * @see DFA.isPrecedenceDfa 20 | */ 21 | public var isPrecedenceDecision: Boolean = false 22 | 23 | override val stateType: Int = 24 | STAR_LOOP_ENTRY 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopbackState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public class StarLoopbackState : ATNState() { 7 | public val loopEntryState: StarLoopEntryState 8 | get() = transition(0).target as StarLoopEntryState 9 | 10 | override val stateType: Int = 11 | STAR_LOOP_BACK 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/TokensStartState.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | /** 7 | * The Tokens rule start state linking to each lexer rule start state. 8 | */ 9 | public class TokensStartState : DecisionState() { 10 | override val stateType: Int = 11 | TOKEN_START 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/atn/WildcardTransition.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.atn 5 | 6 | public class WildcardTransition(target: ATNState) : Transition(target) { 7 | override val serializationType: Int = 8 | WILDCARD 9 | 10 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean = 11 | symbol in minVocabSymbol..maxVocabSymbol 12 | 13 | override fun toString(): String = 14 | "." 15 | } 16 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/dfa/LexerDFASerializer.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.dfa 5 | 6 | import com.strumenta.antlrkotlin.runtime.ext.appendCodePoint 7 | import org.antlr.v4.kotlinruntime.VocabularyImpl 8 | 9 | public class LexerDFASerializer(dfa: DFA) : DFASerializer(dfa, VocabularyImpl.EMPTY_VOCABULARY) { 10 | protected override fun getEdgeLabel(i: Int): String { 11 | val buf = StringBuilder() 12 | buf.append("'") 13 | buf.appendCodePoint(i) 14 | buf.append("'") 15 | return buf.toString() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/AbstractEqualityComparator.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | /** 6 | * This abstract base class is provided so performance-critical applications can 7 | * use virtual-dispatch instead of interface-dispatch when calling comparator methods. 8 | * 9 | * @author Sam Harwell 10 | */ 11 | public abstract class AbstractEqualityComparator : EqualityComparator 12 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/DoubleKeyMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.misc 5 | 6 | /** 7 | * Sometimes we need to map a key to a value but key is two pieces of data. 8 | * This nested hash table saves creating a single key each time we access map; avoids mem creation. 9 | */ 10 | public class DoubleKeyMap { 11 | internal var data: MutableMap> = LinkedHashMap() 12 | 13 | public fun put(k1: Key1, k2: Key2, v: Value): Value? { 14 | var data2 = data[k1] 15 | var prev: Value? = null 16 | 17 | if (data2 == null) { 18 | data2 = LinkedHashMap() 19 | data[k1] = data2 20 | } else { 21 | prev = data2[k2] 22 | } 23 | 24 | data2[k2] = v 25 | return prev 26 | } 27 | 28 | public operator fun get(k1: Key1, k2: Key2): Value? { 29 | val data2 = data[k1] ?: return null 30 | return data2[k2] 31 | } 32 | 33 | public operator fun get(k1: Key1): Map = 34 | data[k1]!! 35 | 36 | /** 37 | * Get all values associated with primary key. 38 | */ 39 | public fun values(k1: Key1): Collection? { 40 | val data2 = data[k1] ?: return null 41 | return data2.values 42 | } 43 | 44 | /** 45 | * Get all primary keys. 46 | */ 47 | public fun keySet(): Set = 48 | data.keys 49 | 50 | /** 51 | * Get all secondary keys associated with a primary key. 52 | */ 53 | public fun keySet(k1: Key1): Set? { 54 | val data2 = data[k1] ?: return null 55 | return data2.keys 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/EqualityComparator.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | /** 6 | * This interface provides an abstract concept of object equality independent of 7 | * [Any.equals] (object equality) and the `==` operator (reference equality). 8 | * 9 | * It can be used to provide algorithm-specific unordered 10 | * comparisons without requiring changes to the object itself. 11 | * 12 | * @author Sam Harwell 13 | */ 14 | public interface EqualityComparator { 15 | 16 | /** 17 | * This method returns a hash code for the specified object. 18 | * 19 | * @param obj The object 20 | * @return The hash code for [obj] 21 | */ 22 | public fun hashCode(obj: T): Int 23 | 24 | /** 25 | * This method tests if two objects are equal. 26 | * 27 | * @param a The first object to compare 28 | * @param b The second object to compare 29 | * @return `true` if [a] equals [b], otherwise `false` 30 | */ 31 | public fun equals(a: T?, b: T?): Boolean 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/IntegerStack.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | /** 6 | * @author Sam Harwell 7 | */ 8 | public class IntegerStack : IntegerList { 9 | public constructor() 10 | public constructor(capacity: Int) : super(capacity) 11 | public constructor(list: IntegerStack) : super(list) 12 | 13 | public fun push(value: Int): Unit = 14 | add(value) 15 | 16 | public fun pop(): Int = 17 | removeAt(size() - 1) 18 | 19 | public fun peek(): Int = 20 | get(size() - 1) 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/MultiMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.misc 5 | 6 | public class MultiMap : MutableMap> by LinkedHashMap() { 7 | public val pairs: List> 8 | get() { 9 | val pairs = ArrayList>() 10 | 11 | for (key in keys) { 12 | for (value in getValue(key)) { 13 | pairs.add(Pair(key, value)) 14 | } 15 | } 16 | 17 | return pairs 18 | } 19 | 20 | public fun map(key: K, value: V) { 21 | var elementsForKey = get(key) 22 | 23 | if (elementsForKey == null) { 24 | elementsForKey = ArrayList() 25 | put(key, elementsForKey) 26 | } 27 | 28 | elementsForKey.add(value) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/ObjectEqualityComparator.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | import kotlin.jvm.JvmField 6 | 7 | /** 8 | * This default implementation of [EqualityComparator] uses object equality 9 | * for comparisons by calling [Any.hashCode] and [Any.equals]. 10 | * 11 | * @author Sam Harwell 12 | */ 13 | public class ObjectEqualityComparator : AbstractEqualityComparator() { 14 | public companion object { 15 | @JvmField 16 | public val INSTANCE: ObjectEqualityComparator = ObjectEqualityComparator() 17 | } 18 | 19 | override fun hashCode(obj: T): Int = 20 | obj?.hashCode() ?: 0 21 | 22 | /** 23 | * This implementation relies on object equality. 24 | * 25 | * If both objects are `null`, this method returns `true`. 26 | * 27 | * Otherwise, if only [a] is `null` this method returns `false`. 28 | * 29 | * Otherwise, this method returns the result of `a == b`. 30 | */ 31 | override fun equals(a: T?, b: T?): Boolean = 32 | (a == null && b == null) || a == b 33 | } 34 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/ParseCancellationException.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.misc 5 | 6 | import org.antlr.v4.kotlinruntime.BailErrorStrategy 7 | import org.antlr.v4.kotlinruntime.RecognitionException 8 | 9 | /** 10 | * This exception is thrown to cancel a parsing operation. This exception does 11 | * not extend [RecognitionException], allowing it to bypass the standard 12 | * error recovery mechanisms. [BailErrorStrategy] throws this exception in 13 | * response to a parse error. 14 | * 15 | * @author Sam Harwell 16 | */ 17 | public class ParseCancellationException : RuntimeException { 18 | public constructor() 19 | public constructor(cause: Throwable) : super(cause) 20 | public constructor(message: String, cause: Throwable? = null) : super(message, cause) 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/misc/Predicate.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.misc 5 | 6 | public interface Predicate { 7 | public fun test(t: T): Boolean 8 | } 9 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNode.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | public interface ErrorNode : TerminalNode 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNodeImpl.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.Token 7 | 8 | /** 9 | * Represents a token that was consumed during resynchronization 10 | * rather than during a valid match operation. For example, 11 | * we will create this kind of node during single token insertion 12 | * and deletion as well as during "consume until error recovery set" 13 | * upon no viable alternative exceptions. 14 | */ 15 | public class ErrorNodeImpl(token: Token) : TerminalNodeImpl(token), ErrorNode { 16 | override fun accept(visitor: ParseTreeVisitor): T = 17 | visitor.visitErrorNode(this) 18 | } 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeListener.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.ParserRuleContext 7 | 8 | /** 9 | * This interface describes the minimal core of methods triggered by [ParseTreeWalker]. 10 | * 11 | * ``` 12 | * val walker = ParseTreeWalker() 13 | * walker.walk(myParseTreeListener, myParseTree) // Triggers events in your listener 14 | * ``` 15 | * 16 | * If you want to trigger events in multiple listeners during a single 17 | * tree walk, you can use the `ParseTreeDispatcher` object available at 18 | * [antlr4#841](https://github.com/antlr/antlr4/issues/841) 19 | */ 20 | public interface ParseTreeListener { 21 | public fun visitTerminal(node: TerminalNode) 22 | public fun visitErrorNode(node: ErrorNode) 23 | public fun enterEveryRule(ctx: ParserRuleContext) 24 | public fun exitEveryRule(ctx: ParserRuleContext) 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeProperty.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import com.strumenta.antlrkotlin.runtime.IdentityHashMap 7 | 8 | /** 9 | * Associate a property with a parse tree node. Useful with parse tree listeners 10 | * that need to associate values with particular tree nodes, kind of like 11 | * specifying a return value for the listener event method that visited a 12 | * particular node. Example: 13 | * 14 | * ``` 15 | * val values = ParseTreeProperty() 16 | * values.put(tree, 36) 17 | * 18 | * val x = values.get(tree) 19 | * values.removeFrom(tree) 20 | * ``` 21 | * 22 | * You would make one decl (values here) in the listener and use lots of times 23 | * in your event methods. 24 | */ 25 | @Suppress("MemberVisibilityCanBePrivate") 26 | public open class ParseTreeProperty { 27 | protected var annotations: MutableMap = IdentityHashMap() 28 | 29 | public operator fun get(node: ParseTree): V? = 30 | annotations[node] 31 | 32 | public fun put(node: ParseTree, value: V) { 33 | annotations[node] = value 34 | } 35 | 36 | public fun removeFrom(node: ParseTree): V? = 37 | annotations.remove(node) 38 | } 39 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeVisitor.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | /** 7 | * This interface defines the basic notion of a parse tree visitor. Generated 8 | * visitors implement this interface and the `XVisitor` interface for grammar `X`. 9 | * 10 | * @param T The return type of the visit operation. 11 | * Use [Unit] for operations with no return type 12 | */ 13 | public interface ParseTreeVisitor { 14 | /** 15 | * Visit a parse tree, and return a user-defined result of the operation. 16 | * 17 | * @param tree The [ParseTree] to visit 18 | * @return The result of visiting the parse tree 19 | */ 20 | public fun visit(tree: ParseTree): T 21 | 22 | /** 23 | * Visit the children of a node, and return a user-defined result of the 24 | * operation. 25 | * 26 | * @param node The [RuleNode] whose children should be visited 27 | * @return The result of visiting the children of the node 28 | */ 29 | public fun visitChildren(node: RuleNode): T 30 | 31 | /** 32 | * Visit a terminal node, and return a user-defined result of the operation. 33 | * 34 | * @param node The [TerminalNode] to visit 35 | * @return The result of visiting the node 36 | */ 37 | public fun visitTerminal(node: TerminalNode): T 38 | 39 | /** 40 | * Visit an error node, and return a user-defined result of the operation. 41 | * 42 | * @param node The [ErrorNode] to visit 43 | * @return The result of visiting the node 44 | */ 45 | public fun visitErrorNode(node: ErrorNode): T 46 | } 47 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/RuleNode.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.RuleContext 7 | 8 | public interface RuleNode : ParseTree { 9 | public val ruleContext: RuleContext 10 | } 11 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/SyntaxTree.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.TokenStream 7 | import org.antlr.v4.kotlinruntime.misc.Interval 8 | 9 | /** 10 | * A tree that knows about an interval in a token stream 11 | * is some kind of syntax tree. Sub-interfaces distinguish 12 | * between parse trees and other kinds of syntax trees we might want to create. 13 | */ 14 | public interface SyntaxTree : Tree { 15 | /** 16 | * Return an [Interval] indicating the index in the [TokenStream] 17 | * of the first and last token associated with this subtree. 18 | * If this node is a leaf, then the interval represents a single 19 | * token and has interval `i..i` for token index `i`. 20 | * 21 | * An interval of `i..i-1` indicates an empty interval at position 22 | * `i` in the input stream, where `0 <= i <=` the size of the input 23 | * token stream. Currently, the code base can only have `i=0..n-1` but 24 | * in concept one could have an empty interval after `EOF`. 25 | * 26 | * If source interval is unknown, this returns [Interval.INVALID]. 27 | * 28 | * As a weird special case, the source interval for rules matched after 29 | * `EOF` is unspecified. 30 | */ 31 | public val sourceInterval: Interval 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/TerminalNode.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.Token 7 | 8 | public interface TerminalNode : ParseTree { 9 | public val symbol: Token 10 | } 11 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/TerminalNodeImpl.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.Parser 7 | import org.antlr.v4.kotlinruntime.RuleContext 8 | import org.antlr.v4.kotlinruntime.Token 9 | import org.antlr.v4.kotlinruntime.misc.Interval 10 | 11 | public open class TerminalNodeImpl(override var symbol: Token) : TerminalNode { 12 | private var parent: ParseTree? = null 13 | 14 | override val childCount: Int = 0 15 | 16 | override val text: String 17 | get() = symbol.text!! 18 | 19 | override val payload: Token 20 | get() = symbol 21 | 22 | override val sourceInterval: Interval 23 | get() { 24 | val tokenIndex = symbol.tokenIndex 25 | return Interval(tokenIndex, tokenIndex) 26 | } 27 | 28 | override fun getParent(): ParseTree? = 29 | parent 30 | 31 | override fun setParent(value: RuleContext?) { 32 | parent = value 33 | } 34 | 35 | override fun getChild(i: Int): ParseTree? = 36 | null 37 | 38 | override fun accept(visitor: ParseTreeVisitor): T = 39 | visitor.visitTerminal(this) 40 | 41 | override fun toStringTree(parser: Parser): String = 42 | toString() 43 | 44 | override fun toString(): String = 45 | if (symbol.type == Token.EOF) { 46 | "" 47 | } else { 48 | symbol.text!! 49 | } 50 | 51 | override fun toStringTree(): String = 52 | toString() 53 | } 54 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/Tree.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree 5 | 6 | import org.antlr.v4.kotlinruntime.RuleContext 7 | import org.antlr.v4.kotlinruntime.Token 8 | 9 | /** 10 | * The basic notion of a tree has a parent, a payload, and a list of children. 11 | * It is the most abstract interface for all the trees used by ANTLR. 12 | */ 13 | public interface Tree { 14 | /** 15 | * This method returns whatever object represents the data at this node. 16 | * For example, for parse trees, the payload can be a [Token] representing 17 | * a leaf node or a [RuleContext] object representing a rule 18 | * invocation. For abstract syntax trees (ASTs), this is a [Token] object. 19 | */ 20 | public val payload: Any? 21 | 22 | /** 23 | * How many children are there? If there is none, then this 24 | * node represents a leaf node. 25 | */ 26 | public val childCount: Int 27 | 28 | /** 29 | * The parent of this node. 30 | * 31 | * If the return value is `null`, then this node is the root of the tree. 32 | */ 33 | public fun getParent(): Tree? 34 | 35 | /** 36 | * If there are children, get the `i`th value indexed from `0`. 37 | */ 38 | public fun getChild(i: Int): Tree? 39 | 40 | /** 41 | * Print out a whole tree, not just a node, in LISP format 42 | * `(root child1 .. childN)`. Print just a node if this is a leaf. 43 | */ 44 | public fun toStringTree(): String 45 | } 46 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/Chunk.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree.pattern 5 | 6 | /** 7 | * A chunk is either a token tag, a rule tag, or a span 8 | * of literal text within a tree pattern. 9 | * 10 | * The method [ParseTreePatternMatcher.split] returns a list of 11 | * chunks in preparation for creating a token stream by 12 | * [ParseTreePatternMatcher.tokenize]. 13 | * 14 | * From there, we get a parse tree from with [ParseTreePatternMatcher.compile]. 15 | * These chunks are converted to [RuleTagToken], [TokenTagToken], or the 16 | * regular tokens of the text surrounding the tags. 17 | */ 18 | internal abstract class Chunk 19 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/TagChunk.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree.pattern 5 | 6 | /** 7 | * Represents a placeholder tag in a tree pattern. 8 | * A tag can have any of the following forms. 9 | * 10 | * - `expr`: An unlabeled placeholder for a parser rule `expr` 11 | * - `ID`: An unlabeled placeholder for a token of type `ID` 12 | * - `e:expr`: A labeled placeholder for a parser rule `expr` 13 | * - `id:ID`: A labeled placeholder for a token of type `ID` 14 | * 15 | * This class does not perform any validation on the tag or label names aside 16 | * from ensuring that the tag is a non-null, non-empty string. 17 | * 18 | * @param label The label, if any, assigned to this chunk 19 | * If this is `null`, the [TagChunk] represents an unlabeled tag 20 | * @param tag The tag for this chunk, which should be the name of a parser rule or token type 21 | * 22 | * @throws IllegalArgumentException If [tag] is empty 23 | */ 24 | internal class TagChunk(val label: String?, val tag: String) : Chunk() { 25 | @Suppress("unused") 26 | constructor(tag: String) : this(null, tag) 27 | 28 | init { 29 | if (tag.isEmpty()) { 30 | throw IllegalArgumentException("tag cannot be null or empty") 31 | } 32 | } 33 | 34 | /** 35 | * This method returns a text representation of the tag chunk. Labeled tags 36 | * are returned in the form `label:tag`, and unlabeled tags are 37 | * returned as just the tag name. 38 | */ 39 | override fun toString(): String = 40 | if (label != null) { 41 | "$label:$tag" 42 | } else { 43 | tag 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/TextChunk.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree.pattern 5 | 6 | /** 7 | * Represents a span of raw text (concrete syntax) between tags in a tree pattern string. 8 | * 9 | * @param text The raw text of this chunk 10 | */ 11 | internal class TextChunk(val text: String) : Chunk() { 12 | /** 13 | * The implementation for [TextChunk] returns the result of [text] in single quotes. 14 | */ 15 | override fun toString(): String = 16 | "'$text'" 17 | } 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/pattern/TokenTagToken.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package org.antlr.v4.kotlinruntime.tree.pattern 5 | 6 | import org.antlr.v4.kotlinruntime.CommonToken 7 | import org.antlr.v4.kotlinruntime.Token 8 | 9 | /** 10 | * A [Token] object representing a token of a particular type; e.g., 11 | * ``. These tokens are created for [TagChunk] chunks where the 12 | * tag corresponds to a lexer rule or token type. 13 | * 14 | * @param tokenName The token name 15 | * @param type The token type 16 | * @param label The label associated with the token tag, or `null` if the token tag is unlabeled 17 | */ 18 | @Suppress("MemberVisibilityCanBePrivate") 19 | public class TokenTagToken( 20 | public val tokenName: String, type: Int, 21 | public val label: String? = null, 22 | ) : CommonToken(type) { 23 | /** 24 | * The implementation for [TokenTagToken] returns the token tag formatted with `<` and `>` delimiters. 25 | */ 26 | @Suppress("SuspiciousVarProperty") 27 | override var text: String? = null 28 | get() = if (label != null) { 29 | "<$label:$tokenName>" 30 | } else { 31 | "<$tokenName>" 32 | } 33 | 34 | /** 35 | * The implementation for [TokenTagToken] returns a string of the form `tokenName:type`. 36 | */ 37 | override fun toString(): String = 38 | "$tokenName:$type" 39 | } 40 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | 7 | @Suppress("MemberVisibilityCanBePrivate") 8 | public abstract class XPathElement(protected var nodeName: String) { 9 | public var invert: Boolean = false 10 | 11 | /** 12 | * Given tree rooted at [t], returns all nodes matched by this path element. 13 | */ 14 | public abstract fun evaluate(t: ParseTree): Collection 15 | 16 | override fun toString(): String { 17 | val inv = if (invert) "!" else "" 18 | val className = this::class.simpleName 19 | return "$className[$inv$nodeName]" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathLexerErrorListener.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.BaseErrorListener 6 | import org.antlr.v4.kotlinruntime.RecognitionException 7 | import org.antlr.v4.kotlinruntime.Recognizer 8 | 9 | public open class XPathLexerErrorListener : BaseErrorListener() { 10 | override fun syntaxError( 11 | recognizer: Recognizer<*, *>, 12 | offendingSymbol: Any?, 13 | line: Int, 14 | charPositionInLine: Int, 15 | msg: String, 16 | e: RecognitionException?, 17 | ) { 18 | // Noop 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathRuleAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | import org.antlr.v4.kotlinruntime.tree.Trees 7 | 8 | /** 9 | * Either `ID` at start of path or `...//ID` in middle of path. 10 | */ 11 | public open class XPathRuleAnywhereElement(ruleName: String, protected var ruleIndex: Int) : XPathElement(ruleName) { 12 | override fun evaluate(t: ParseTree): Collection = 13 | Trees.findAllRuleNodes(t, ruleIndex) 14 | } 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathRuleElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.ParserRuleContext 6 | import org.antlr.v4.kotlinruntime.tree.ParseTree 7 | import org.antlr.v4.kotlinruntime.tree.Trees 8 | 9 | public open class XPathRuleElement(ruleName: String, protected var ruleIndex: Int) : XPathElement(ruleName) { 10 | override fun evaluate(t: ParseTree): Collection { 11 | // Return all children of t that match nodeName 12 | val children = Trees.getChildren(t) 13 | val nodes = ArrayList(children.size) 14 | 15 | for (c in children) { 16 | if (c is ParserRuleContext) { 17 | if (c.ruleIndex == ruleIndex && !invert || c.ruleIndex != ruleIndex && invert) { 18 | nodes.add(c) 19 | } 20 | } 21 | } 22 | 23 | return nodes 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathTokenAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | import org.antlr.v4.kotlinruntime.tree.Trees 7 | 8 | @Suppress("MemberVisibilityCanBePrivate") 9 | public open class XPathTokenAnywhereElement(tokenName: String, protected var tokenType: Int) : XPathElement(tokenName) { 10 | override fun evaluate(t: ParseTree): Collection = 11 | Trees.findAllTokenNodes(t, tokenType) 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathTokenElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | import org.antlr.v4.kotlinruntime.tree.TerminalNode 7 | import org.antlr.v4.kotlinruntime.tree.Trees 8 | 9 | @Suppress("MemberVisibilityCanBePrivate") 10 | public open class XPathTokenElement(tokenName: String, protected var tokenType: Int) : XPathElement(tokenName) { 11 | override fun evaluate(t: ParseTree): Collection { 12 | // Return all children of t that match nodeName 13 | val children = Trees.getChildren(t) 14 | val nodes = ArrayList(children.size) 15 | 16 | for (c in children) { 17 | if (c is TerminalNode) { 18 | if (c.symbol.type == tokenType && !invert || c.symbol.type != tokenType && invert) { 19 | nodes.add(c) 20 | } 21 | } 22 | } 23 | 24 | return nodes 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathWildcardAnywhereElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | import org.antlr.v4.kotlinruntime.tree.Trees 7 | 8 | public open class XPathWildcardAnywhereElement : XPathElement(XPath.WILDCARD) { 9 | override fun evaluate(t: ParseTree): Collection = 10 | if (invert) { 11 | // !* is weird but valid (empty) 12 | emptyList() 13 | } else { 14 | Trees.getDescendants(t) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonMain/kotlin/org/antlr/v4/kotlinruntime/tree/xpath/XPathWildcardElement.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.tree.xpath 4 | 5 | import org.antlr.v4.kotlinruntime.tree.ParseTree 6 | import org.antlr.v4.kotlinruntime.tree.Trees 7 | 8 | public open class XPathWildcardElement : XPathElement(XPath.WILDCARD) { 9 | override fun evaluate(t: ParseTree): Collection { 10 | if (invert) { 11 | // !* is weird but valid (empty) 12 | return emptyList() 13 | } 14 | 15 | val children = Trees.getChildren(t) 16 | val kids = ArrayList(children.size) 17 | 18 | for (c in children) { 19 | kids.add(c as ParseTree) 20 | } 21 | 22 | return kids 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonTest/kotlin/StringTest.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | import kotlin.test.Test 4 | import kotlin.test.assertContentEquals 5 | import kotlin.test.assertEquals 6 | 7 | class StringTest { 8 | @Test 9 | fun testAsCharArrayEmpty() { 10 | assertContentEquals(charArrayOf(), "".toCharArray()) 11 | } 12 | 13 | @Test 14 | fun testAsCharArrayEmptyLength() { 15 | assertEquals(0, "".toCharArray().size) 16 | } 17 | 18 | @Test 19 | fun testAsCharArrayEmptyEl0() { 20 | assertEquals('a', "abc def".toCharArray()[0]) 21 | } 22 | 23 | @Test 24 | fun testAsCharArray() { 25 | assertContentEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray()) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/commonTest/kotlin/org/antlr/v4/kotlinruntime/misc/IntegerListTest.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | import kotlin.test.Test 6 | import kotlin.test.assertEquals 7 | 8 | class IntegerListTest { 9 | @Test 10 | fun addToIntegerList() { 11 | val il = IntegerList() 12 | il.add(10) 13 | 14 | assertEquals(1, il.size()) 15 | assertEquals(10, il[0]) 16 | } 17 | 18 | @Test 19 | fun removeAtIntegerList() { 20 | val il = IntegerList() 21 | il.add(10) 22 | il.add(12) 23 | il.add(14) 24 | il.add(16) 25 | il.removeAt(2) 26 | 27 | assertEquals(3, il.size()) 28 | assertEquals(10, il[0]) 29 | assertEquals(12, il[1]) 30 | assertEquals(16, il[2]) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsAndWasmSharedMain/kotlin/com/strumenta/antlrkotlin/runtime/CopyOnWriteArrayList.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // Note(Edoardo): JS is single threaded, so a normal list is good enough 6 | internal actual typealias CopyOnWriteArrayList = ArrayList 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsAndWasmSharedMain/kotlin/com/strumenta/antlrkotlin/runtime/Synchronized.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlin.contracts.ExperimentalContracts 6 | import kotlin.contracts.InvocationKind 7 | import kotlin.contracts.contract 8 | 9 | // Not necessary for JavaScript. Single threaded. 10 | @OptIn(ExperimentalContracts::class) 11 | internal actual inline fun synchronized(lock: Any, block: () -> R): R { 12 | contract { 13 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 14 | } 15 | 16 | return block() 17 | } 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsAndWasmSharedMain/kotlin/com/strumenta/antlrkotlin/runtime/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // Note(Edoardo): this is implemented as an HashMap in the JS target, 6 | // so let's keep it as it is 7 | internal actual typealias WeakHashMap = HashMap 8 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsAndWasmSharedMain/kotlin/org/antlr/v4/kotlinruntime/CharStreams.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | public actual object CharStreams : AbstractCharStreams() 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | @file:Suppress("NOTHING_TO_INLINE") 4 | 5 | package com.strumenta.antlrkotlin.runtime 6 | 7 | internal actual inline fun platformPrintErrLn(): Unit = 8 | console.error("") 9 | 10 | internal actual inline fun platformPrintErrLn(message: String): Unit = 11 | console.error(message) 12 | 13 | internal actual inline fun platformPrintErr(message: String): Unit = 14 | console.error(message) 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/Environment.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual fun platformGetEnv(name: String): String? { 6 | if (isNodeJs()) { 7 | return js("process.env[name]").unsafeCast() 8 | } 9 | 10 | System.out.println("Environment variables are not supported in the browser") 11 | return null 12 | } 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityKeysView.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal class IdentityKeysView(private val map: IdentityHashMap) : AbstractMutableSet() { 6 | override val size: Int 7 | get() = map.size 8 | 9 | override fun isEmpty(): Boolean = 10 | map.isEmpty() 11 | 12 | override fun clear(): Unit = 13 | map.clear() 14 | 15 | override fun contains(element: K): Boolean = 16 | map.containsKey(element) 17 | 18 | override fun add(element: K): Boolean = 19 | throw UnsupportedOperationException("Adding is not supported on keys") 20 | 21 | override fun remove(element: K): Boolean = 22 | map.removeBoolean(element) 23 | 24 | override fun removeAll(elements: Collection): Boolean { 25 | var removed = false 26 | 27 | for (element in elements) { 28 | removed = remove(element) || removed 29 | } 30 | 31 | return removed 32 | } 33 | 34 | override fun iterator(): MutableIterator { 35 | val entriesIterator = map.entries.iterator() 36 | return object : MutableIterator { 37 | override fun hasNext(): Boolean = 38 | entriesIterator.hasNext() 39 | 40 | override fun next(): K = 41 | entriesIterator.next().key 42 | 43 | override fun remove(): Unit = 44 | entriesIterator.remove() 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityValuesView.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal class IdentityValuesView(private val map: IdentityHashMap<*, V>) : AbstractMutableCollection() { 6 | override val size: Int 7 | get() = map.size 8 | 9 | override fun isEmpty(): Boolean = 10 | map.isEmpty() 11 | 12 | override fun clear(): Unit = 13 | map.clear() 14 | 15 | override fun add(element: V): Boolean = 16 | throw UnsupportedOperationException("Adding is not supported on values") 17 | 18 | override fun remove(element: V): Boolean { 19 | val iterator = iterator() 20 | 21 | while (iterator.hasNext()) { 22 | // IMPORTANT: notice that we use reference/strict equality 23 | if (iterator.next() === element) { 24 | iterator.remove() 25 | return true 26 | } 27 | } 28 | 29 | return false 30 | } 31 | 32 | override fun removeAll(elements: Collection): Boolean { 33 | var removed = false 34 | 35 | for (element in elements) { 36 | removed = remove(element) || removed 37 | } 38 | 39 | return removed 40 | } 41 | 42 | override operator fun contains(element: V): Boolean = 43 | map.containsValue(element) 44 | 45 | override operator fun iterator(): MutableIterator { 46 | val entriesIterator = map.entries.iterator() 47 | return object : MutableIterator { 48 | override fun hasNext(): Boolean = 49 | entriesIterator.hasNext() 50 | 51 | override fun next(): V = 52 | entriesIterator.next().value 53 | 54 | override fun remove(): Unit = 55 | entriesIterator.remove() 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public actual typealias JsName = kotlin.js.JsName 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jsMain/kotlin/com/strumenta/antlrkotlin/runtime/JsUtils.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | @file:Suppress("NOTHING_TO_INLINE", "UnsafeCastFromDynamic") 4 | 5 | package com.strumenta.antlrkotlin.runtime 6 | 7 | /** 8 | * Normalizes potentially `undefined` values to `null`. 9 | */ 10 | internal inline fun undefinedToNull(value: T): T = 11 | if (value === js("undefined")) js("null") else value 12 | 13 | /** 14 | * Creates a new generic array with an initial [size], 15 | * without requiring the initialization of the elements. 16 | */ 17 | @Suppress("UNUSED_PARAMETER") 18 | internal inline fun newArray(size: Int): Array = 19 | js("Array(size)") 20 | 21 | /** 22 | * Returns whether we are running on Node.js, or not. 23 | */ 24 | internal fun isNodeJs(): Boolean = 25 | js( 26 | """ 27 | (typeof process !== 'undefined' 28 | && process.versions != null 29 | && process.versions.node != null) || 30 | (typeof window !== 'undefined' 31 | && typeof window.process !== 'undefined' 32 | && window.process.versions != null 33 | && window.process.versions.node != null) 34 | """ 35 | ) 36 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/BitSet.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package com.strumenta.antlrkotlin.runtime 5 | 6 | import java.util.BitSet as JavaBitSet 7 | 8 | public actual typealias BitSet = JavaBitSet 9 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | @file:Suppress("NOTHING_TO_INLINE") 4 | 5 | package com.strumenta.antlrkotlin.runtime 6 | 7 | import java.lang.System as JavaSystem 8 | 9 | internal actual inline fun platformPrintErrLn(): Unit = 10 | JavaSystem.err.println() 11 | 12 | internal actual inline fun platformPrintErrLn(message: String): Unit = 13 | JavaSystem.err.println(message) 14 | 15 | internal actual inline fun platformPrintErr(message: String): Unit = 16 | JavaSystem.err.print(message) 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/CopyOnWriteArrayList.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual typealias CopyOnWriteArrayList = java.util.concurrent.CopyOnWriteArrayList 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/Environment.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import java.lang.System as JavaSystem 6 | 7 | @Suppress("NOTHING_TO_INLINE") 8 | internal actual inline fun platformGetEnv(name: String): String? = 9 | JavaSystem.getenv(name) 10 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import java.util.IdentityHashMap as JavaIdentityHashMap 6 | 7 | internal actual typealias IdentityHashMap = JavaIdentityHashMap 8 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | @Target( 6 | AnnotationTarget.CLASS, 7 | AnnotationTarget.FUNCTION, 8 | AnnotationTarget.PROPERTY, 9 | AnnotationTarget.CONSTRUCTOR, 10 | AnnotationTarget.PROPERTY_GETTER, 11 | AnnotationTarget.PROPERTY_SETTER, 12 | ) 13 | @Retention(AnnotationRetention.SOURCE) 14 | public actual annotation class JsName(actual val name: String) 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/Synchronized.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual inline fun synchronized(lock: Any, block: () -> R): R = 6 | kotlin.synchronized(lock, block) 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/jvmMain/kotlin/com/strumenta/antlrkotlin/runtime/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import java.util.WeakHashMap as JavaWeakHashMap 6 | 7 | internal actual typealias WeakHashMap = JavaWeakHashMap 8 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/linuxMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual fun androidPrintErr(message: String): Unit = error("Should not be called") 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/mingwMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual fun androidPrintErr(message: String): Unit = error("Should not be called") 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/BitSet.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | 4 | package com.strumenta.antlrkotlin.runtime 5 | 6 | public actual typealias BitSet = SimpleBitSet 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlinx.cinterop.ExperimentalForeignApi 6 | import platform.posix.fflush 7 | import platform.posix.fprintf 8 | import platform.posix.stderr 9 | import kotlin.experimental.ExperimentalNativeApi 10 | 11 | // Must throw an exception in all platforms but Android 12 | internal expect fun androidPrintErr(message: String) 13 | 14 | internal actual fun platformPrintErrLn(): Unit = 15 | printImpl(lineBreak) 16 | 17 | internal actual fun platformPrintErrLn(message: String): Unit = 18 | printImpl("$message$lineBreak") 19 | 20 | internal actual fun platformPrintErr(message: String): Unit = 21 | printImpl(message) 22 | 23 | @OptIn(ExperimentalNativeApi::class) 24 | private val lineBreak = if (Platform.osFamily == OsFamily.WINDOWS) "\r\n" else "\n" 25 | 26 | // Let me explain what is going on here, why we have a generic 27 | // function for all native targets and a specific one for Android. 28 | // 29 | // Why can't we simply declare nativePrintErr an expect function 30 | // and implement it in appleMain/linuxMain/mingwMain/androidNativeMain? 31 | // 32 | // The answer is fprintf and fflush are not available under appleMain 33 | // for some reason, even if they should be, and thus the compilation fails. 34 | // This strategy is a temporary workaround until the problem is fixed. 35 | 36 | @OptIn(ExperimentalNativeApi::class) 37 | private val printImpl = if (Platform.osFamily == OsFamily.ANDROID) ::androidPrintErr else ::nativePrintErr 38 | 39 | @OptIn(ExperimentalForeignApi::class) 40 | private fun nativePrintErr(message: String) { 41 | fprintf(stderr, message) 42 | fflush(stderr) 43 | } 44 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/CopyOnWriteArrayList.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): make thread safe at some point 6 | internal actual typealias CopyOnWriteArrayList = ArrayList 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/Environment.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlinx.cinterop.ExperimentalForeignApi 6 | import kotlinx.cinterop.toKString 7 | import platform.posix.getenv 8 | 9 | @OptIn(ExperimentalForeignApi::class) 10 | @Suppress("NOTHING_TO_INLINE") 11 | internal actual inline fun platformGetEnv(name: String): String? = 12 | getenv(name)?.toKString() 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): implement real identity comparison 6 | internal actual typealias IdentityHashMap = HashMap 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | @Target( 6 | AnnotationTarget.CLASS, 7 | AnnotationTarget.FUNCTION, 8 | AnnotationTarget.PROPERTY, 9 | AnnotationTarget.CONSTRUCTOR, 10 | AnnotationTarget.PROPERTY_GETTER, 11 | AnnotationTarget.PROPERTY_SETTER, 12 | ) 13 | @Retention(AnnotationRetention.SOURCE) 14 | public actual annotation class JsName(actual val name: String) 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/Synchronized.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlin.contracts.ExperimentalContracts 6 | import kotlin.contracts.InvocationKind 7 | import kotlin.contracts.contract 8 | 9 | @OptIn(ExperimentalContracts::class) 10 | internal actual inline fun synchronized(lock: Any, block: () -> R): R { 11 | contract { 12 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 13 | } 14 | 15 | return block() 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/com/strumenta/antlrkotlin/runtime/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): implement real weak keys. 6 | // See kotlinlang.org/api/latest/jvm/stdlib/kotlin.native.ref 7 | // for classes and functions useful for a possible implementation 8 | internal actual typealias WeakHashMap = HashMap 9 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/nativeMain/kotlin/org/antlr/v4/kotlinruntime/CharStreams.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | public actual object CharStreams : AbstractCharStreams() 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/BitSet.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public actual typealias BitSet = SimpleBitSet 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/Console.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | internal actual fun platformPrintErrLn(): Unit = 6 | js("console.error('')") 7 | 8 | internal actual fun platformPrintErrLn(message: String): Unit = 9 | js("console.error(message)") 10 | 11 | internal actual fun platformPrintErr(message: String): Unit = 12 | js("console.error(message)") 13 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/Environment.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | @Suppress("UNUSED_PARAMETER", "RedundantNullableReturnType") 6 | private fun processEnvJs(name: String): String? = 7 | js("process.env[name]") 8 | 9 | internal actual fun platformGetEnv(name: String): String? { 10 | if (isNodeJs()) { 11 | return processEnvJs(name) 12 | } 13 | 14 | System.out.println("Environment variables are not supported in the browser") 15 | return null 16 | } 17 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): implement real identity comparison 6 | internal actual typealias IdentityHashMap = HashMap 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/IsNodeJs.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | /** 6 | * Returns whether we are running on Node.js, or not. 7 | */ 8 | internal fun isNodeJs(): Boolean = 9 | js( 10 | """ 11 | (typeof process !== 'undefined' 12 | && process.versions != null 13 | && process.versions.node != null) || 14 | (typeof window !== 'undefined' 15 | && typeof window.process !== 'undefined' 16 | && window.process.versions != null 17 | && window.process.versions.node != null) 18 | """ 19 | ) 20 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmJsMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public actual typealias JsName = kotlin.js.JsName 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/BitSet.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | public actual typealias BitSet = SimpleBitSet 6 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/CopyOnWriteArrayList.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // Note(Edoardo): WASI is single threaded at the moment, so a normal list is good enough 6 | internal actual typealias CopyOnWriteArrayList = ArrayList 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/IdentityHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): implement real identity comparison 6 | internal actual typealias IdentityHashMap = HashMap 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/JsName.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | @Target( 6 | AnnotationTarget.CLASS, 7 | AnnotationTarget.FUNCTION, 8 | AnnotationTarget.PROPERTY, 9 | AnnotationTarget.CONSTRUCTOR, 10 | AnnotationTarget.PROPERTY_GETTER, 11 | AnnotationTarget.PROPERTY_SETTER, 12 | ) 13 | @Retention(AnnotationRetention.SOURCE) 14 | public actual annotation class JsName(actual val name: String) 15 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/Synchronized.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | import kotlin.contracts.ExperimentalContracts 6 | import kotlin.contracts.InvocationKind 7 | import kotlin.contracts.contract 8 | 9 | // Not necessary for WASI. Single threaded. 10 | @OptIn(ExperimentalContracts::class) 11 | internal actual inline fun synchronized(lock: Any, block: () -> R): R { 12 | contract { 13 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 14 | } 15 | 16 | return block() 17 | } 18 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/com/strumenta/antlrkotlin/runtime/WeakHashMap.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.runtime 4 | 5 | // TODO(Edoardo): implement real weak keys 6 | internal actual typealias WeakHashMap = HashMap 7 | -------------------------------------------------------------------------------- /antlr-kotlin-runtime/src/wasmWasiMain/kotlin/org/antlr/v4/kotlinruntime/CharStreams.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime 4 | 5 | public actual object CharStreams : AbstractCharStreams() 6 | -------------------------------------------------------------------------------- /antlr-kotlin-target/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.strumenta.antlrkotlin.gradle.ext.setupPom 2 | import com.vanniktech.maven.publish.SonatypeHost 3 | 4 | plugins { 5 | id("strumenta.jvm.library") 6 | id("org.jetbrains.dokka") 7 | } 8 | 9 | dependencies { 10 | api(libs.antlr4) 11 | } 12 | 13 | mavenPublishing { 14 | coordinates( 15 | groupId = project.group as String, 16 | artifactId = project.name, 17 | version = project.version as String, 18 | ) 19 | 20 | setupPom(project, projectDescription = "Kotlin target for ANTLR") 21 | publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, true) 22 | signAllPublications() 23 | } 24 | 25 | tasks { 26 | findByName("generateMetadataFileForMavenPublication")?.dependsOn("kotlinSourcesJar") 27 | } 28 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/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-tests/antlr/SimpleExpr.g4: -------------------------------------------------------------------------------- 1 | grammar SimpleExpr; 2 | 3 | eval returns [double value] 4 | : exp=additionExp { $value = $exp.value } 5 | ; 6 | 7 | additionExp returns [double value] 8 | : m1=multiplyExp { $value = $m1.value } 9 | ( '+' m2=multiplyExp { $value += $m2.value } 10 | | '-' m2=multiplyExp { $value -= $m2.value } 11 | )* 12 | ; 13 | 14 | multiplyExp returns [double value] 15 | : a1=atomExp { $value = $a1.value } 16 | ( '*' a2=atomExp { $value *= $a2.value } 17 | | '/' a2=atomExp { $value /= $a2.value } 18 | )* 19 | ; 20 | 21 | atomExp returns [double value] 22 | : n=NUMBER { $value = $n.text.toDouble() } 23 | | '(' exp=additionExp ')' { $value = $exp.value } 24 | ; 25 | 26 | NUMBER: ('0'..'9')+ ('.' ('1'..'9')+)?; 27 | WS: (' ' | '\t' | '\r'| '\n') -> channel(HIDDEN); 28 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/antlr/SizedList.g4: -------------------------------------------------------------------------------- 1 | grammar SizedList; 2 | 3 | stringList: 4 | size=int 5 | items=stringSequence[$size.value] 6 | EOF; 7 | 8 | int returns [value: Int]: 9 | NUM 10 | { 11 | $value = $NUM.text.toInt() 12 | }; 13 | 14 | stringSequence[count: Int] returns [value: MutableList] locals [remaining: Int]: 15 | { 16 | $value = mutableListOf() 17 | $remaining = $count 18 | } 19 | ( 20 | {$remaining!! > 0}? STRING 21 | { 22 | $value!! += $STRING.text 23 | $remaining = $remaining!! - 1 24 | } 25 | )*; 26 | 27 | STRING: [a-z]+; 28 | NUM: [0-9]+; 29 | WHITESPACE: [ \t\r\n]+ -> skip; -------------------------------------------------------------------------------- /antlr-kotlin-tests/antlr/XPathExpr.g4: -------------------------------------------------------------------------------- 1 | grammar XPathExpr; 2 | 3 | prog 4 | : func+ 5 | ; 6 | 7 | func 8 | : 'def' ID '(' arg (',' arg)* ')' body 9 | ; 10 | 11 | body 12 | : '{' stat+ '}' 13 | ; 14 | 15 | arg 16 | : ID 17 | ; 18 | 19 | stat 20 | : expr ';' # printExpr 21 | | ID '=' expr ';' # assign 22 | | 'return' expr ';' # ret 23 | | ';' # blank 24 | ; 25 | 26 | expr 27 | : expr ('*'|'/') expr # MulDiv 28 | | expr ('+'|'-') expr # AddSub 29 | | primary # prim 30 | ; 31 | 32 | primary 33 | : INT # int 34 | | ID # id 35 | | '(' expr ')' # parens 36 | ; 37 | 38 | MUL: '*'; // Assigns token name to '*' used above in grammar 39 | DIV: '/'; 40 | ADD: '+'; 41 | SUB: '-'; 42 | RETURN: 'return'; 43 | ID: [a-zA-Z]+; // Match identifiers 44 | INT: [0-9]+; // Match integers 45 | NEWLINE: '\r'? '\n' -> skip; // Return newlines to parser (is end-statement signal) 46 | WS: [ \t]+ -> skip; // Toss out whitespace 47 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/antlr/XPathLexer.g4: -------------------------------------------------------------------------------- 1 | lexer grammar XPathLexer; 2 | 3 | tokens { 4 | TokenRef, 5 | RuleRef 6 | } 7 | 8 | Anywhere : '//'; 9 | Root : '/'; 10 | Wildcard : '*'; 11 | Bang : '!'; 12 | Id : NAME_START_CHAR NAME_CHAR* { 13 | val text = this.text; 14 | 15 | type = if (text[0].isUpperCase()) { 16 | Tokens.TokenRef; 17 | } else { 18 | Tokens.RuleRef; 19 | } 20 | }; 21 | String : '\'' .*? '\''; 22 | 23 | fragment NAME_CHAR 24 | : [\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nl}\p{Pc}\p{Nd}\p{Mc}\p{Mn}\p{Cf}\u0000-\u0008\u000E-\u001B\u007F-\u009F]; 25 | 26 | fragment NAME_START_CHAR 27 | : [\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nl}]; 28 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonMain/kotlin/com/strumenta/antlrkotlin/test/CPP14ParserBase.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test 2 | 3 | import com.strumenta.antlrkotlin.test.generated.CPP14Parser 4 | import org.antlr.v4.kotlinruntime.Parser 5 | import org.antlr.v4.kotlinruntime.TokenStream 6 | 7 | // Note(Edoardo): this is adapted from antlr/grammars-v4/cpp/java 8 | public abstract class CPP14ParserBase(input: TokenStream) : Parser(input) { 9 | @Suppress("FunctionName") 10 | protected fun IsPureSpecifierAllowed(): Boolean { 11 | try { 12 | val x = this.context!! // memberDeclarator 13 | val c = x.getChild(0)!!.getChild(0) 14 | val c2 = c!!.getChild(0) 15 | val p = c2!!.getChild(1) ?: return false 16 | return p is CPP14Parser.ParametersAndQualifiersContext 17 | } catch (_: Exception) { 18 | // Noop 19 | } 20 | 21 | return false 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/SyntaxErrorsErrorListener.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test 2 | 3 | import org.antlr.v4.kotlinruntime.BaseErrorListener 4 | import org.antlr.v4.kotlinruntime.RecognitionException 5 | import org.antlr.v4.kotlinruntime.Recognizer 6 | 7 | /** 8 | * Accumulates syntax errors while parsing. 9 | */ 10 | class SyntaxErrorsErrorListener : BaseErrorListener() { 11 | private var errorMessages = ArrayList(16) 12 | 13 | val errors: List 14 | get() = errorMessages 15 | 16 | override fun syntaxError( 17 | recognizer: Recognizer<*, *>, 18 | offendingSymbol: Any?, 19 | line: Int, 20 | charPositionInLine: Int, 21 | msg: String, 22 | e: RecognitionException?, 23 | ) { 24 | errorMessages.add("line $line:$charPositionInLine $msg") 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/ThrowingErrorListener.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test 2 | 3 | import org.antlr.v4.kotlinruntime.BaseErrorListener 4 | import org.antlr.v4.kotlinruntime.RecognitionException 5 | import org.antlr.v4.kotlinruntime.Recognizer 6 | 7 | /** 8 | * A recognition error listener that simply throws an [IllegalStateException] 9 | * when a syntax error occurs, effectively stopping the parsing process 10 | * and any other activity. 11 | */ 12 | object ThrowingErrorListener : BaseErrorListener() { 13 | override fun syntaxError( 14 | recognizer: Recognizer<*, *>, 15 | offendingSymbol: Any?, 16 | line: Int, 17 | charPositionInLine: Int, 18 | msg: String, 19 | e: RecognitionException?, 20 | ) { 21 | val message = "Token recognition error at line $line, column $charPositionInLine: $msg" 22 | throw IllegalStateException(message, e) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/grammars/CPP14GrammarTest.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test.grammars 2 | 3 | import com.strumenta.antlrkotlin.test.GrammarTest 4 | import com.strumenta.antlrkotlin.test.generated.CPP14Lexer 5 | import com.strumenta.antlrkotlin.test.generated.CPP14Parser 6 | import org.antlr.v4.kotlinruntime.CharStream 7 | import org.antlr.v4.kotlinruntime.ParserRuleContext 8 | import org.antlr.v4.kotlinruntime.TokenStream 9 | 10 | @Suppress("unused") 11 | class CPP14GrammarTest : GrammarTest() { 12 | override fun createLexer(input: CharStream): CPP14Lexer = 13 | CPP14Lexer(input) 14 | 15 | override fun createParser(input: TokenStream): CPP14Parser = 16 | CPP14Parser(input) 17 | 18 | override fun setupTreeTestRuns(runs: MutableSet) { 19 | runs += LispTestRun("cpp/test.cpp", "cpp/test.cpp.tree") 20 | runs += LispTestRun("cpp/macro.cpp", "cpp/macro.cpp.tree") 21 | } 22 | 23 | override fun setupErrorsTestRuns(runs: MutableSet) { 24 | // No test runs 25 | } 26 | 27 | override fun getTree(parser: CPP14Parser): ParserRuleContext = 28 | parser.translationUnit() 29 | } 30 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/grammars/Css3GrammarTest.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test.grammars 2 | 3 | import com.strumenta.antlrkotlin.test.GrammarTest 4 | import com.strumenta.antlrkotlin.test.generated.css3Lexer 5 | import com.strumenta.antlrkotlin.test.generated.css3Parser 6 | import org.antlr.v4.kotlinruntime.CharStream 7 | import org.antlr.v4.kotlinruntime.ParserRuleContext 8 | import org.antlr.v4.kotlinruntime.TokenStream 9 | 10 | @Suppress("unused") 11 | class Css3GrammarTest : GrammarTest() { 12 | override fun createLexer(input: CharStream): css3Lexer = 13 | css3Lexer(input) 14 | 15 | override fun createParser(input: TokenStream): css3Parser = 16 | css3Parser(input) 17 | 18 | override fun setupTreeTestRuns(runs: MutableSet) { 19 | runs += LispTestRun("css3/at-rule.css", "css3/at-rule.css.tree") 20 | } 21 | 22 | override fun setupErrorsTestRuns(runs: MutableSet) { 23 | // No test runs 24 | } 25 | 26 | override fun getTree(parser: css3Parser): ParserRuleContext = 27 | parser.stylesheet() 28 | } 29 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/grammars/SizedListGrammarTest.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test.grammars 2 | 3 | import com.strumenta.antlrkotlin.test.GrammarTest 4 | import com.strumenta.antlrkotlin.test.generated.SizedListLexer 5 | import com.strumenta.antlrkotlin.test.generated.SizedListParser 6 | import org.antlr.v4.kotlinruntime.CharStream 7 | import org.antlr.v4.kotlinruntime.TokenStream 8 | 9 | @Suppress("unused") 10 | class SizedListGrammarTest : GrammarTest() { 11 | override fun createLexer(input: CharStream) = SizedListLexer(input) 12 | 13 | override fun createParser(input: TokenStream) = SizedListParser(input) 14 | 15 | override fun setupTreeTestRuns(runs: MutableSet) { 16 | runs += LispTestRun("sizedList/five.sl", "sizedList/five.sl.tree") 17 | } 18 | 19 | override fun setupErrorsTestRuns(runs: MutableSet) { 20 | runs += ErrorsTestRun("sizedList/oneTooMany.sl", "sizedList/oneTooMany.sl.errors") 21 | } 22 | 23 | override fun getTree(parser: SizedListParser) = parser.stringList() 24 | } 25 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/grammars/Vb6GrammarTest.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.test.grammars 2 | 3 | import com.strumenta.antlrkotlin.test.GrammarTest 4 | import com.strumenta.antlrkotlin.test.generated.VisualBasic6Lexer 5 | import com.strumenta.antlrkotlin.test.generated.VisualBasic6Parser 6 | import org.antlr.v4.kotlinruntime.CharStream 7 | import org.antlr.v4.kotlinruntime.ParserRuleContext 8 | import org.antlr.v4.kotlinruntime.TokenStream 9 | 10 | @Suppress("unused") 11 | class Vb6GrammarTest : GrammarTest() { 12 | override fun createLexer(input: CharStream): VisualBasic6Lexer = 13 | VisualBasic6Lexer(input) 14 | 15 | override fun createParser(input: TokenStream): VisualBasic6Parser = 16 | VisualBasic6Parser(input) 17 | 18 | override fun setupTreeTestRuns(runs: MutableSet) { 19 | // No test runs 20 | } 21 | 22 | override fun setupErrorsTestRuns(runs: MutableSet) { 23 | runs += ErrorsTestRun("vb6/form1.vb", "vb6/form1.vb.errors") 24 | } 25 | 26 | override fun getTree(parser: VisualBasic6Parser): ParserRuleContext = 27 | parser.startRule() 28 | } 29 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/test/minicalc/LocalListener.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Martin Gittins 2018. 3 | * User: martingittins 4 | * Date: 13/06/2018 5 | * Time: 09:52 6 | */ 7 | package com.strumenta.antlrkotlin.test.minicalc 8 | 9 | import com.strumenta.antlrkotlin.test.generated.MiniCalcParser 10 | import com.strumenta.antlrkotlin.test.generated.MiniCalcParserBaseListener 11 | import org.antlr.v4.kotlinruntime.tree.ParseTree 12 | 13 | @Suppress("UNUSED_PARAMETER") 14 | class LocalListener : MiniCalcParserBaseListener() { 15 | override fun exitMiniCalcFile(ctx: MiniCalcParser.MiniCalcFileContext) { 16 | ctx.children!!.forEach { line -> 17 | processLine(line) 18 | } 19 | } 20 | 21 | private fun processLine(line: ParseTree) { 22 | processStatement(line.getChild(0)!!) 23 | } 24 | 25 | private fun processStatement(statement: ParseTree) { 26 | val content = statement.getChild(0)!! 27 | 28 | when (statement) { 29 | is MiniCalcParser.InputDeclarationStatementContext -> processInputDeclStatement(content) 30 | is MiniCalcParser.VarDeclarationStatementContext -> processVarDeclStatement(content) 31 | is MiniCalcParser.AssignmentStatementContext -> processAssignmentStatement(content) 32 | is MiniCalcParser.PrintStatementContext -> processPrintStatement(content) 33 | } 34 | } 35 | 36 | private fun processPrintStatement(content: ParseTree) { 37 | println("called processPrintStatement") 38 | } 39 | 40 | private fun processAssignmentStatement(content: ParseTree) { 41 | println("called processAssignmentStatement") 42 | } 43 | 44 | private fun processVarDeclStatement(content: ParseTree) { 45 | println("called processVarDeclStatement") 46 | } 47 | 48 | private fun processInputDeclStatement(content: ParseTree) { 49 | println("called processInputDeclStatement") 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/com/strumenta/antlrkotlin/util/Resources.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package com.strumenta.antlrkotlin.util 4 | 5 | import com.goncalossilva.resources.Resource 6 | 7 | /** 8 | * Loads a test resource, typically located under the `/resources` directory, as a byte sequence. 9 | * 10 | * @see loadBytes 11 | */ 12 | fun loadResourceBytes(path: String): ByteArray { 13 | val resource = Resource(path) 14 | return resource.readBytes() 15 | } 16 | 17 | /** 18 | * Loads a test resource, typically located under the `/resources` directory, as UTF-8 encoded text. 19 | * 20 | * @see loadText 21 | */ 22 | fun loadResourceText(path: String): String { 23 | val resource = Resource(path) 24 | return resource.readText() 25 | } 26 | 27 | /** 28 | * Utility extension function to load bytes from a string representing a resource path. 29 | * 30 | * @see loadResourceBytes 31 | */ 32 | fun String.loadBytes(basePath: String = "src/commonTest/resources"): ByteArray = 33 | loadResourceBytes("$basePath/$this") 34 | 35 | /** 36 | * Utility extension function to load text from a string representing a resource path. 37 | * 38 | * @see loadResourceText 39 | */ 40 | fun String.loadText(basePath: String = "src/commonTest/resources"): String = 41 | loadResourceText("$basePath/$this") 42 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/kotlin/org/antlr/v4/kotlinruntime/misc/InterpreterDataReaderTest.kt: -------------------------------------------------------------------------------- 1 | // Copyright 2017-present Strumenta and contributors, licensed under Apache 2.0. 2 | // Copyright 2024-present Strumenta and contributors, licensed under BSD 3-Clause. 3 | package org.antlr.v4.kotlinruntime.misc 4 | 5 | import com.strumenta.antlrkotlin.runtime.StringLineReader 6 | import com.strumenta.antlrkotlin.util.loadText 7 | import org.antlr.v4.kotlinruntime.VocabularyImpl 8 | import org.antlr.v4.kotlinruntime.atn.ATNDeserializer 9 | import org.antlr.v4.kotlinruntime.atn.ATNSerializer 10 | import kotlin.test.Test 11 | import kotlin.test.assertContentEquals 12 | import kotlin.test.assertEquals 13 | import kotlin.test.assertNull 14 | 15 | class InterpreterDataReaderTest { 16 | @Test 17 | fun testInterpFile() { 18 | // Based on the grammar found in org.antlr.v4.test.runtime.java.TestInterpreterDataReader 19 | val interpContent = "test.interp".loadText() 20 | val reader = StringLineReader(interpContent) 21 | val data = InterpreterDataReader.parse(reader) 22 | val vocabulary = data.vocabulary as VocabularyImpl 23 | 24 | assertEquals(6, vocabulary.maxTokenType) 25 | assertContentEquals(listOf("s", "expr"), data.ruleNames) 26 | assertContentEquals(arrayOf("", "", "'*'", "'/'", "'+'", "'-'", ""), vocabulary.literalNames) 27 | assertContentEquals(arrayOf("", "INT", "MUL", "DIV", "ADD", "SUB", "WS"), vocabulary.symbolicNames) 28 | assertNull(data.channels) 29 | assertNull(data.modes) 30 | 31 | val serialized = ATNSerializer.getSerialized(data.atn) 32 | assertEquals(ATNDeserializer.SERIALIZED_VERSION, serialized[0]) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/cpp/macro.cpp: -------------------------------------------------------------------------------- 1 | #define Verify(cond, msg) \ 2 | do \ 3 | { \ 4 | if (!(cond)) \ 5 | { \ 6 | verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \ 7 | } \ 8 | } while (0) 9 | 10 | void f() { 11 | int b = 0; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/cpp/macro.cpp.tree: -------------------------------------------------------------------------------- 1 | (translationUnit (declarationseq (declaration (functionDefinition (declSpecifierSeq (declSpecifier (typeSpecifier (trailingTypeSpecifier (simpleTypeSpecifier void))))) (declarator (pointerDeclarator (noPointerDeclarator (noPointerDeclarator (declaratorid (idExpression (unqualifiedId f)))) (parametersAndQualifiers ( ))))) (functionBody (compoundStatement { (statementSeq (statement (declarationStatement (blockDeclaration (simpleDeclaration (declSpecifierSeq (declSpecifier (typeSpecifier (trailingTypeSpecifier (simpleTypeSpecifier int))))) (initDeclaratorList (initDeclarator (declarator (pointerDeclarator (noPointerDeclarator (declaratorid (idExpression (unqualifiedId b)))))) (initializer (braceOrEqualInitializer = (initializerClause (assignmentExpression (conditionalExpression (logicalOrExpression (logicalAndExpression (inclusiveOrExpression (exclusiveOrExpression (andExpression (equalityExpression (relationalExpression (shiftExpression (additiveExpression (multiplicativeExpression (pointerMemberExpression (castExpression (unaryExpression (postfixExpression (primaryExpression (literal 0))))))))))))))))))))))) ;))))) }))))) ) -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/cpp/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | int main() 8 | { 9 | //CPP14 grammar:parse error when writing a string in multiple lines #1381 10 | string str1 = "rafeeque_" 11 | "Aazam" 12 | "Ansar"; 13 | cout << str1; 14 | 15 | 16 | _getch(); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/css3/at-rule.css: -------------------------------------------------------------------------------- 1 | @foo { 2 | @bar {} 3 | } -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/css3/at-rule.css.tree: -------------------------------------------------------------------------------- 1 | (stylesheet ws (nestedStatement (atRule @foo (ws ) (block { (ws \n ) (nestedStatement (atRule @bar (ws ) (block { ws } (ws \n)))) } ws))) ) -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/sizedList/five.sl: -------------------------------------------------------------------------------- 1 | 5 2 | one 3 | two 4 | three 5 | four 6 | five -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/sizedList/five.sl.tree: -------------------------------------------------------------------------------- 1 | (stringList (int 5) (stringSequence one two three four five) ) -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/sizedList/oneTooMany.sl: -------------------------------------------------------------------------------- 1 | 5 2 | one 3 | two 4 | three 5 | four 6 | five 7 | six -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/sizedList/oneTooMany.sl.errors: -------------------------------------------------------------------------------- 1 | line 7:0 no viable alternative at input 'six' -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/test.interp: -------------------------------------------------------------------------------- 1 | token literal names: 2 | null 3 | null 4 | '*' 5 | '/' 6 | '+' 7 | '-' 8 | null 9 | 10 | token symbolic names: 11 | null 12 | INT 13 | MUL 14 | DIV 15 | ADD 16 | SUB 17 | WS 18 | 19 | rule names: 20 | s 21 | expr 22 | 23 | 24 | atn: 25 | [4, 1, 6, 22, 2, 0, 7, 0, 2, 1, 7, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 17, 8, 1, 10, 1, 12, 1, 20, 9, 1, 1, 1, 0, 1, 2, 2, 0, 2, 0, 2, 1, 0, 2, 3, 1, 0, 4, 5, 21, 0, 4, 1, 0, 0, 0, 2, 7, 1, 0, 0, 0, 4, 5, 3, 2, 1, 0, 5, 6, 5, 0, 0, 1, 6, 1, 1, 0, 0, 0, 7, 8, 6, 1, -1, 0, 8, 9, 5, 1, 0, 0, 9, 18, 1, 0, 0, 0, 10, 11, 10, 2, 0, 0, 11, 12, 7, 0, 0, 0, 12, 17, 3, 2, 1, 3, 13, 14, 10, 1, 0, 0, 14, 15, 7, 1, 0, 0, 15, 17, 3, 2, 1, 2, 16, 10, 1, 0, 0, 0, 16, 13, 1, 0, 0, 0, 17, 20, 1, 0, 0, 0, 18, 16, 1, 0, 0, 0, 18, 19, 1, 0, 0, 0, 19, 3, 1, 0, 0, 0, 20, 18, 1, 0, 0, 0, 2, 16, 18] -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/tsql/constants.sql: -------------------------------------------------------------------------------- 1 | create procedure sp (@val numeric) as begin print @val end 2 | go 3 | exec sp $5 4 | go 5 | exec sp $-5 6 | go 7 | exec sp $+5 8 | go 9 | exec sp -$5 10 | go 11 | exec sp -$-5 12 | go 13 | exec sp +$-5 -- should fail 14 | go 15 | exec sp -1 16 | go 17 | exec sp - -1 -- should fail 18 | go 19 | exec sp +1 -- should fail 20 | go 21 | select $5 22 | go 23 | select $-5 24 | go 25 | select $+5 26 | go 27 | select -$5 28 | go 29 | select -$-5 30 | go 31 | select +$-5 32 | go 33 | select -1 34 | go 35 | select - -1 36 | go 37 | select +1 38 | go 39 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/vb6/form1.vb: -------------------------------------------------------------------------------- 1 | Public Class Form1 2 | 3 | Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 4 | ' Create two buttons to use as the accept and cancel buttons. 5 | Dim button1 As New Button() 6 | Dim button2 As New Button() 7 | ' Set the text of button1 to "OK". 8 | button1.Text = "OK" 9 | ' Set the position of the button on the form. 10 | button1.Location = New Point(10, 10) 11 | ' Set the text of button2 to "Cancel". 12 | button2.Text = "Cancel" 13 | ' Set the position of the button based on the location of button1. 14 | button2.Location = _ 15 | New Point(button1.Left, button1.Height + button1.Top + 10) 16 | ' Set the caption bar text of the form. 17 | Me.Text = "tutorialspoint.com" 18 | ' Display a help button on the form. 19 | Me.HelpButton = True 20 | ' Define the border style of the form to a dialog box. 21 | Me.FormBorderStyle = FormBorderStyle.FixedDialog 22 | ' Set the MaximizeBox to false to remove the maximize box. 23 | Me.MaximizeBox = False 24 | ' Set the MinimizeBox to false to remove the minimize box. 25 | Me.MinimizeBox = False 26 | ' Set the accept button of the form to button1. 27 | Me.AcceptButton = button1 28 | ' Set the cancel button of the form to button2. 29 | Me.CancelButton = button2 30 | ' Set the start position of the form to the center of the screen. 31 | Me.StartPosition = FormStartPosition.CenterScreen 32 | ' Set window width and height 33 | Me.Height = 300 34 | Me.Width = 560 35 | ' Add button1 to the form. 36 | Me.Controls.Add(button1) 37 | ' Add button2 to the form. 38 | Me.Controls.Add(button2) 39 | End Sub 40 | End Class 41 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/commonTest/resources/vb6/form1.vb.errors: -------------------------------------------------------------------------------- 1 | line 1:13 mismatched input 'Form1' expecting 2 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/jsTest/kotlin/com/strumenta/antlrkotlin/test/grammars/TSqlGrammarJsTest.kt: -------------------------------------------------------------------------------- 1 | // This is needed as the IDE is not able to properly reference 2 | // the TSqlParser class as it is too big 3 | @file:Suppress("UNRESOLVED_REFERENCE") 4 | 5 | package com.strumenta.antlrkotlin.test.grammars 6 | 7 | import com.strumenta.antlrkotlin.test.GrammarTest 8 | import com.strumenta.antlrkotlin.test.generated.TSqlLexer 9 | import com.strumenta.antlrkotlin.test.generated.TSqlParser 10 | import org.antlr.v4.kotlinruntime.CharStream 11 | import org.antlr.v4.kotlinruntime.ParserRuleContext 12 | import org.antlr.v4.kotlinruntime.TokenStream 13 | 14 | // Note(Edoardo): move the test back to commonTest once 15 | // the MethodTooLargeException has been solved on the JVM 16 | // by the Kotlin team. 17 | // FQN: org.jetbrains.org.objectweb.asm.MethodTooLargeException 18 | @Suppress("unused") 19 | class TSqlGrammarJsTest : GrammarTest() { 20 | override fun createLexer(input: CharStream): TSqlLexer = 21 | TSqlLexer(input) 22 | 23 | override fun createParser(input: TokenStream): TSqlParser = 24 | TSqlParser(input) 25 | 26 | override fun setupTreeTestRuns(runs: MutableSet) { 27 | runs += LispTestRun("tsql/hints.sql", "tsql/hints.sql.tree") 28 | } 29 | 30 | override fun setupErrorsTestRuns(runs: MutableSet) { 31 | runs += ErrorsTestRun("tsql/constants.sql", "tsql/constants.sql.errors") 32 | } 33 | 34 | override fun getTree(parser: TSqlParser): ParserRuleContext = 35 | parser.tsql_file() 36 | } 37 | -------------------------------------------------------------------------------- /antlr-kotlin-tests/src/nativeTest/kotlin/com/strumenta/antlrkotlin/test/grammars/TSqlGrammarNativeTest.kt: -------------------------------------------------------------------------------- 1 | // This is needed as the IDE is not able to properly reference 2 | // the TSqlParser class as it is too big 3 | @file:Suppress("UNRESOLVED_REFERENCE") 4 | 5 | package com.strumenta.antlrkotlin.test.grammars 6 | 7 | import com.strumenta.antlrkotlin.test.GrammarTest 8 | import com.strumenta.antlrkotlin.test.generated.TSqlLexer 9 | import com.strumenta.antlrkotlin.test.generated.TSqlParser 10 | import org.antlr.v4.kotlinruntime.CharStream 11 | import org.antlr.v4.kotlinruntime.ParserRuleContext 12 | import org.antlr.v4.kotlinruntime.TokenStream 13 | 14 | // Note(Edoardo): move the test back to commonTest once 15 | // the MethodTooLargeException has been solved on the JVM 16 | // by the Kotlin team. 17 | // FQN: org.jetbrains.org.objectweb.asm.MethodTooLargeException 18 | @Suppress("unused") 19 | class TSqlGrammarNativeTest : GrammarTest() { 20 | override fun createLexer(input: CharStream): TSqlLexer = 21 | TSqlLexer(input) 22 | 23 | override fun createParser(input: TokenStream): TSqlParser = 24 | TSqlParser(input) 25 | 26 | override fun setupTreeTestRuns(runs: MutableSet) { 27 | runs += LispTestRun("tsql/hints.sql", "tsql/hints.sql.tree") 28 | } 29 | 30 | override fun setupErrorsTestRuns(runs: MutableSet) { 31 | runs += ErrorsTestRun("tsql/constants.sql", "tsql/constants.sql.errors") 32 | } 33 | 34 | override fun getTree(parser: TSqlParser): ParserRuleContext = 35 | parser.tsql_file() 36 | } 37 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.strumenta.antlrkotlin.gradle.ext.mavenRepositoryName 2 | import com.strumenta.antlrkotlin.gradle.ext.mavenRepositoryUrl 3 | import org.gradle.api.tasks.testing.logging.TestExceptionFormat 4 | 5 | plugins { 6 | alias(libs.plugins.researchgate.release) 7 | id("com.vanniktech.maven.publish") apply false 8 | } 9 | 10 | allprojects { 11 | group = "com.strumenta" 12 | 13 | apply(plugin = "com.vanniktech.maven.publish") 14 | 15 | // Allow publishing to a private Maven repository, other than to Maven Central 16 | val privateRepoUrl = mavenRepositoryUrl() 17 | 18 | if (privateRepoUrl != null) { 19 | extensions.configure("publishing") { 20 | repositories { 21 | maven { 22 | name = mavenRepositoryName() ?: "PrivateNexus" 23 | url = uri(privateRepoUrl) 24 | isAllowInsecureProtocol = true 25 | } 26 | } 27 | } 28 | } 29 | } 30 | 31 | subprojects { 32 | tasks.withType().all { 33 | testLogging { 34 | showStandardStreams = true 35 | showExceptions = true 36 | exceptionFormat = TestExceptionFormat.FULL 37 | } 38 | } 39 | } 40 | 41 | release { 42 | buildTasks = listOf( 43 | ":antlr-kotlin-runtime:publishAllPublicationsToMavenCentralRepository", 44 | ":antlr-kotlin-target:publishAllPublicationsToMavenCentralRepository", 45 | ":antlr-kotlin-gradle-plugin:publishPlugins", 46 | ) 47 | 48 | git { 49 | requireBranch = "" 50 | pushToRemote = "origin" 51 | } 52 | } 53 | 54 | tasks { 55 | wrapper { 56 | distributionType = Wrapper.DistributionType.ALL 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /buildSrc/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | } 4 | 5 | dependencies { 6 | // The Kotlin Gradle Plugin dependency propagates to the entire workspace 7 | implementation(libs.kotlin.plugin) 8 | implementation(libs.maven.publish.plugin) 9 | implementation(libs.dokka.plugin) 10 | implementation(libs.gradle.plugin.publish.plugin) 11 | } 12 | 13 | gradlePlugin { 14 | plugins { 15 | register("strumentaJvmLibrary") { 16 | id = "strumenta.jvm.library" 17 | implementationClass = "com.strumenta.antlrkotlin.gradle.plugins.StrumentaJvmLibraryModulePlugin" 18 | } 19 | 20 | register("strumentaMultiplatform") { 21 | id = "strumenta.multiplatform" 22 | implementationClass = "com.strumenta.antlrkotlin.gradle.plugins.StrumentaMultiplatformModulePlugin" 23 | } 24 | 25 | register("strumentaGradlePlugin") { 26 | id = "strumenta.gradle.plugin" 27 | implementationClass = "com.strumenta.antlrkotlin.gradle.plugins.StrumentaGradlePluginModulePlugin" 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /buildSrc/gradle.properties: -------------------------------------------------------------------------------- 1 | # Do not automatically add the kotlin-stdlib dependency 2 | kotlin.stdlib.default.dependency = false 3 | -------------------------------------------------------------------------------- /buildSrc/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "buildSrc" 2 | 3 | dependencyResolutionManagement { 4 | @Suppress("UnstableApiUsage") 5 | repositories { 6 | mavenCentral() 7 | gradlePluginPortal() 8 | } 9 | 10 | versionCatalogs { 11 | create("libs") { 12 | from(files("../gradle/libs.versions.toml")) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/com/strumenta/antlrkotlin/gradle/ext/MavenPublishBaseExtension.ext.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.gradle.ext 2 | 3 | import com.vanniktech.maven.publish.MavenPublishBaseExtension 4 | import org.gradle.api.Project 5 | 6 | fun MavenPublishBaseExtension.setupPom(project: Project, projectDescription: String) { 7 | pom { 8 | name.set(project.name) 9 | description.set(projectDescription) 10 | url.set("https://github.com/Strumenta/antlr-kotlin") 11 | 12 | scm { 13 | connection.set("scm:git:https://github.com/Strumenta/antlr-kotlin.git") 14 | developerConnection.set("scm:git:git@github.com:Strumenta/antlr-kotlin.git") 15 | url.set("https://github.com/Strumenta/antlr-kotlin.git") 16 | } 17 | 18 | licenses { 19 | license { 20 | name.set("Apache License V2.0") 21 | url.set("https://www.apache.org/licenses/LICENSE-2.0") 22 | distribution.set("repo") 23 | } 24 | license { 25 | name.set("BSD 3-Clause") 26 | url.set("https://opensource.org/license/bsd-3-clause/") 27 | distribution.set("repo") 28 | } 29 | } 30 | 31 | // The developers entry is strictly required by Maven Central 32 | developers { 33 | developer { 34 | id.set("ftomassetti") 35 | name.set("Federico Tomassetti") 36 | email.set("federico@strumenta.com") 37 | } 38 | developer { 39 | id.set("lppedd") 40 | name.set("Edoardo Luppi") 41 | email.set("lp.edoardo@gmail.com") 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/com/strumenta/antlrkotlin/gradle/plugins/StrumentaGradlePluginModulePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.gradle.plugins 2 | 3 | import com.gradle.publish.PublishPlugin 4 | import com.strumenta.antlrkotlin.gradle.ext.javaExtension 5 | import com.strumenta.antlrkotlin.gradle.ext.kotlinJvmExtension 6 | import org.gradle.api.JavaVersion 7 | import org.gradle.api.Plugin 8 | import org.gradle.api.Project 9 | import org.gradle.kotlin.dsl.apply 10 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget 11 | import org.jetbrains.kotlin.gradle.dsl.KotlinVersion 12 | import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper 13 | 14 | /** 15 | * Applies and set up the necessary dependencies to develop a Gradle Plugin. 16 | */ 17 | class StrumentaGradlePluginModulePlugin : Plugin { 18 | override fun apply(project: Project) { 19 | // Apply the required plugins 20 | project.apply() 21 | project.apply() 22 | project.apply { 23 | plugin("org.gradle.java-gradle-plugin") 24 | } 25 | 26 | // General Kotlin configuration 27 | val kotlin = project.kotlinJvmExtension 28 | kotlin.explicitApiWarning() 29 | kotlin.compilerOptions { 30 | apiVersion.set(KotlinVersion.KOTLIN_2_1) 31 | languageVersion.set(KotlinVersion.KOTLIN_2_1) 32 | 33 | jvmTarget.set(JvmTarget.JVM_1_8) 34 | freeCompilerArgs.add("-Xjvm-default=all") 35 | } 36 | 37 | val java = project.javaExtension 38 | java.sourceCompatibility = JavaVersion.VERSION_1_8 39 | java.targetCompatibility = JavaVersion.VERSION_1_8 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/com/strumenta/antlrkotlin/gradle/plugins/StrumentaJvmLibraryModulePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.gradle.plugins 2 | 3 | import com.strumenta.antlrkotlin.gradle.ext.javaExtension 4 | import com.strumenta.antlrkotlin.gradle.ext.kotlinJvmExtension 5 | import org.gradle.api.JavaVersion 6 | import org.gradle.api.Plugin 7 | import org.gradle.api.Project 8 | import org.gradle.kotlin.dsl.apply 9 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget 10 | import org.jetbrains.kotlin.gradle.dsl.KotlinVersion 11 | import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper 12 | 13 | /** 14 | * Applies and set up the Kotlin JVM Gradle plugin. 15 | */ 16 | class StrumentaJvmLibraryModulePlugin : Plugin { 17 | override fun apply(project: Project) { 18 | // Apply the required plugins 19 | project.apply() 20 | 21 | // General Kotlin configuration 22 | val kotlin = project.kotlinJvmExtension 23 | kotlin.explicitApiWarning() 24 | kotlin.compilerOptions { 25 | apiVersion.set(KotlinVersion.KOTLIN_2_1) 26 | languageVersion.set(KotlinVersion.KOTLIN_2_1) 27 | 28 | jvmTarget.set(JvmTarget.JVM_1_8) 29 | freeCompilerArgs.add("-Xjvm-default=all") 30 | } 31 | 32 | val java = project.javaExtension 33 | java.sourceCompatibility = JavaVersion.VERSION_1_8 34 | java.targetCompatibility = JavaVersion.VERSION_1_8 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/com/strumenta/antlrkotlin/gradle/plugins/StrumentaMultiplatformModulePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.strumenta.antlrkotlin.gradle.plugins 2 | 3 | import com.strumenta.antlrkotlin.gradle.ext.kmpExtension 4 | import org.gradle.api.Plugin 5 | import org.gradle.api.Project 6 | import org.gradle.kotlin.dsl.apply 7 | import org.gradle.kotlin.dsl.create 8 | import org.jetbrains.kotlin.gradle.dsl.KotlinVersion 9 | import org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginWrapper 10 | import org.jetbrains.kotlin.gradle.targets.js.yarn.yarn 11 | 12 | /** 13 | * Applies and set up the Kotlin Multiplatform Gradle plugin. 14 | * 15 | * @see StrumentaMultiplatformModuleExtension 16 | */ 17 | class StrumentaMultiplatformModulePlugin : Plugin { 18 | override fun apply(project: Project) { 19 | // Apply the required plugins 20 | project.apply() 21 | 22 | // Register an extension to allow configuring the plugin using 23 | // 24 | // strumentaMultiplatform { 25 | // ... 26 | // } 27 | project.extensions.create("strumentaMultiplatform", project) 28 | 29 | // Disable a nagging console (fake) error. 30 | // See https://youtrack.jetbrains.com/issue/KT-52578 31 | val yarn = project.yarn 32 | yarn.ignoreScripts = false 33 | 34 | // General Kotlin multiplatform configuration 35 | val kmp = project.kmpExtension 36 | kmp.explicitApiWarning() 37 | kmp.compilerOptions { 38 | apiVersion.set(KotlinVersion.KOTLIN_2_1) 39 | languageVersion.set(KotlinVersion.KOTLIN_2_1) 40 | freeCompilerArgs.add("-Xexpect-actual-classes") 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | ######################### 2 | # Gradle settings 3 | ######################### 4 | org.gradle.jvmargs = -Xmx6g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8 5 | org.gradle.parallel = true 6 | org.gradle.caching = true 7 | org.gradle.configuration-cache = true 8 | 9 | ######################### 10 | # Kotlin settings 11 | ######################### 12 | kotlin.code.style = official 13 | 14 | ######################### 15 | # Project settings 16 | ######################### 17 | version = 1.0.6-SNAPSHOT 18 | target.is.native = true 19 | 20 | # Publish to a private repository 21 | repo.snapshot.name = 22 | repo.snapshot.url = 23 | repo.release.name = 24 | repo.release.url = 25 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | kotlin = "2.1.20" 3 | kotlinx-io = "0.7.0" 4 | kotlinx-benchmark = "0.4.14" 5 | kotlinx-resources = "0.10.0" 6 | antlr4 = "4.13.1" 7 | dokka = "1.9.20" 8 | researchgate-release = "3.1.0" 9 | maven-publish = "0.32.0" 10 | gradle-plugin-publish = "1.3.0" 11 | antlr-kotlin = "1.0.4" 12 | 13 | [libraries] 14 | kotlinx-io-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-io-core", version.ref = "kotlinx-io" } 15 | kotlinx-benchmark = { group = "org.jetbrains.kotlinx", name = "kotlinx-benchmark-runtime", version.ref = "kotlinx-benchmark" } 16 | kotlinx-resources = { group = "com.goncalossilva", name = "resources", version.ref = "kotlinx-resources" } 17 | antlr4 = { group = "org.antlr", name = "antlr4", version.ref = "antlr4" } 18 | 19 | # Gradle 20 | kotlin-plugin = { group = "org.jetbrains.kotlin", name = "kotlin-gradle-plugin", version.ref = "kotlin" } 21 | dokka-plugin = { group = "org.jetbrains.dokka", name = "dokka-gradle-plugin", version.ref = "dokka" } 22 | maven-publish-plugin = { group = "com.vanniktech", name = "gradle-maven-publish-plugin", version.ref = "maven-publish" } 23 | gradle-plugin-publish-plugin = { group = "com.gradle.publish", name = "plugin-publish-plugin", version.ref = "gradle-plugin-publish" } 24 | 25 | [plugins] 26 | kotlin-allopen = { id = "org.jetbrains.kotlin.plugin.allopen", version.ref = "kotlin" } 27 | kotlinx-benchmark = { id = "org.jetbrains.kotlinx.benchmark", version.ref = "kotlinx-benchmark" } 28 | kotlinx-resources = { id = "com.goncalossilva.resources", version.ref = "kotlinx-resources" } 29 | researchgate-release = { id = "net.researchgate.release", version.ref = "researchgate-release" } 30 | antlr-kotlin = { id = "com.strumenta.antlr-kotlin", version.ref = "antlr-kotlin" } 31 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Strumenta/antlr-kotlin/ec50f85c67f5c9e8a1fe87a64b0a27ea5365adfe/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 2 | 3 | dependencyResolutionManagement { 4 | @Suppress("UnstableApiUsage") 5 | repositories { 6 | mavenCentral() 7 | } 8 | } 9 | 10 | rootProject.name = "antlr-kotlin" 11 | 12 | include("antlr-kotlin-target") 13 | include("antlr-kotlin-runtime") 14 | include("antlr-kotlin-benchmarks") 15 | include("antlr-kotlin-tests") 16 | include("antlr-kotlin-gradle-plugin") 17 | --------------------------------------------------------------------------------