32 | // The default value is {@code false} to avoid the performance and memory
33 | // overhead of copying text for every token unless explicitly requested.
46 | // This token factory does not explicitly copy token text when constructing
47 | // tokens.
48 | //
49 | CommonTokenFactory.DEFAULT = new CommonTokenFactory();
50 |
51 | CommonTokenFactory.prototype.create = function(source, type, text, channel, start, stop, line, column) {
52 | var t = new CommonToken(source, type, channel, start, stop);
53 | t.line = line;
54 | t.column = column;
55 | if (text !==null) {
56 | t.text = text;
57 | } else if (this.copyText && source[1] !==null) {
58 | t.text = source[1].getText(start,stop);
59 | }
60 | return t;
61 | };
62 |
63 | CommonTokenFactory.prototype.createThin = function(type, text) {
64 | var t = new CommonToken(null, type);
65 | t.text = text;
66 | return t;
67 | };
68 |
69 | exports.CommonTokenFactory = CommonTokenFactory;
70 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/FileStream.js:
--------------------------------------------------------------------------------
1 | //
2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | //
7 |
8 | //
9 | // This is an InputStream that is loaded from a file all at once
10 | // when you construct the object.
11 | //
12 | var InputStream = require('./InputStream').InputStream;
13 | var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
14 | var fs = isNodeJs ? require("fs") : null;
15 |
16 | function FileStream(fileName, decodeToUnicodeCodePoints) {
17 | var data = fs.readFileSync(fileName, "utf8");
18 | InputStream.call(this, data, decodeToUnicodeCodePoints);
19 | this.fileName = fileName;
20 | return this;
21 | }
22 |
23 | FileStream.prototype = Object.create(InputStream.prototype);
24 | FileStream.prototype.constructor = FileStream;
25 |
26 | exports.FileStream = FileStream;
27 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/README.md:
--------------------------------------------------------------------------------
1 | # JavaScript target for ANTLR 4
2 |
3 | JavaScript runtime libraries for ANTLR 4
4 |
5 | This runtime is available through npm. The package name is 'antlr4'.
6 |
7 | This runtime has been tested in Node.js, Safari, Firefox, Chrome and IE.
8 |
9 | See www.antlr.org for more information on ANTLR
10 |
11 | See https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md for more information on using ANTLR in JavaScript
12 |
13 |
14 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/atn/ATNDeserializationOptions.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 |
6 | function ATNDeserializationOptions(copyFrom) {
7 | if(copyFrom===undefined) {
8 | copyFrom = null;
9 | }
10 | this.readOnly = false;
11 | this.verifyATN = copyFrom===null ? true : copyFrom.verifyATN;
12 | this.generateRuleBypassTransitions = copyFrom===null ? false : copyFrom.generateRuleBypassTransitions;
13 |
14 | return this;
15 | }
16 |
17 | ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions();
18 | ATNDeserializationOptions.defaultOptions.readOnly = true;
19 |
20 | // def __setattr__(self, key, value):
21 | // if key!="readOnly" and self.readOnly:
22 | // raise Exception("The object is read only.")
23 | // super(type(self), self).__setattr__(key,value)
24 |
25 | exports.ATNDeserializationOptions = ATNDeserializationOptions;
26 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/atn/ATNSimulator.js:
--------------------------------------------------------------------------------
1 | //
2 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | ///
7 |
8 | var DFAState = require('./../dfa/DFAState').DFAState;
9 | var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet;
10 | var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext;
11 |
12 | function ATNSimulator(atn, sharedContextCache) {
13 |
14 | // The context cache maps all PredictionContext objects that are ==
15 | // to a single cached copy. This cache is shared across all contexts
16 | // in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet
17 | // to use only cached nodes/graphs in addDFAState(). We don't want to
18 | // fill this during closure() since there are lots of contexts that
19 | // pop up but are not used ever again. It also greatly slows down closure().
20 | //
21 | //
This cache makes a huge difference in memory and a little bit in speed.
22 | // For the Java grammar on java.*, it dropped the memory requirements
23 | // at the end from 25M to 16M. We don't store any of the full context
24 | // graphs in the DFA because they are limited to local context only,
25 | // but apparently there's a lot of repetition there as well. We optimize
26 | // the config contexts before storing the config set in the DFA states
27 | // by literally rebuilding them with cached subgraphs only.
28 | //
29 | //
I tried a cache for use during closure operations, that was
30 | // whacked after each adaptivePredict(). It cost a little bit
31 | // more time I think and doesn't save on the overall footprint
32 | // so it's not worth the complexity.
33 | ///
34 | this.atn = atn;
35 | this.sharedContextCache = sharedContextCache;
36 | return this;
37 | }
38 |
39 | // Must distinguish between missing edge and edge we know leads nowhere///
40 | ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet());
41 |
42 |
43 | ATNSimulator.prototype.getCachedContext = function(context) {
44 | if (this.sharedContextCache ===null) {
45 | return context;
46 | }
47 | var visited = {};
48 | return getCachedPredictionContext(context, this.sharedContextCache, visited);
49 | };
50 |
51 | exports.ATNSimulator = ATNSimulator;
52 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/atn/ATNType.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 | ///
6 |
7 | // Represents the type of recognizer an ATN applies to.
8 |
9 | function ATNType() {
10 |
11 | }
12 |
13 | ATNType.LEXER = 0;
14 | ATNType.PARSER = 1;
15 |
16 | exports.ATNType = ATNType;
17 |
18 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/atn/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 |
6 | exports.ATN = require('./ATN').ATN;
7 | exports.ATNDeserializer = require('./ATNDeserializer').ATNDeserializer;
8 | exports.LexerATNSimulator = require('./LexerATNSimulator').LexerATNSimulator;
9 | exports.ParserATNSimulator = require('./ParserATNSimulator').ParserATNSimulator;
10 | exports.PredictionMode = require('./PredictionMode').PredictionMode;
11 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/dfa/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 |
6 | exports.DFA = require('./DFA').DFA;
7 | exports.DFASerializer = require('./DFASerializer').DFASerializer;
8 | exports.LexerDFASerializer = require('./DFASerializer').LexerDFASerializer;
9 | exports.PredPrediction = require('./DFAState').PredPrediction;
10 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/error/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 |
6 | exports.RecognitionException = require('./Errors').RecognitionException;
7 | exports.NoViableAltException = require('./Errors').NoViableAltException;
8 | exports.LexerNoViableAltException = require('./Errors').LexerNoViableAltException;
9 | exports.InputMismatchException = require('./Errors').InputMismatchException;
10 | exports.FailedPredicateException = require('./Errors').FailedPredicateException;
11 | exports.DiagnosticErrorListener = require('./DiagnosticErrorListener').DiagnosticErrorListener;
12 | exports.BailErrorStrategy = require('./ErrorStrategy').BailErrorStrategy;
13 | exports.ErrorListener = require('./ErrorListener').ErrorListener;
14 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 | exports.atn = require('./atn/index');
6 | exports.codepointat = require('./polyfills/codepointat');
7 | exports.dfa = require('./dfa/index');
8 | exports.fromcodepoint = require('./polyfills/fromcodepoint');
9 | exports.tree = require('./tree/index');
10 | exports.error = require('./error/index');
11 | exports.Token = require('./Token').Token;
12 | exports.CharStreams = require('./CharStreams').CharStreams;
13 | exports.CommonToken = require('./Token').CommonToken;
14 | exports.InputStream = require('./InputStream').InputStream;
15 | exports.FileStream = require('./FileStream').FileStream;
16 | exports.CommonTokenStream = require('./CommonTokenStream').CommonTokenStream;
17 | exports.Lexer = require('./Lexer').Lexer;
18 | exports.Parser = require('./Parser').Parser;
19 | var pc = require('./PredictionContext');
20 | exports.PredictionContextCache = pc.PredictionContextCache;
21 | exports.ParserRuleContext = require('./ParserRuleContext').ParserRuleContext;
22 | exports.Interval = require('./IntervalSet').Interval;
23 | exports.Utils = require('./Utils');
24 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "antlr4",
3 | "version": "4.7.1",
4 | "description": "JavaScript runtime for ANTLR4",
5 | "main": "src/antlr4/index.js",
6 | "repository": "antlr/antlr4.git",
7 | "keywords": [
8 | "lexer",
9 | "parser",
10 | "antlr",
11 | "antlr4",
12 | "grammar"
13 | ],
14 | "license": "BSD",
15 | "bugs": {
16 | "url": "https://github.com/antlr/antlr4/issues"
17 | },
18 | "homepage": "https://github.com/antlr/antlr4"
19 | }
20 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/polyfills/codepointat.js:
--------------------------------------------------------------------------------
1 | /*! https://mths.be/codepointat v0.2.0 by @mathias */
2 | if (!String.prototype.codePointAt) {
3 | (function() {
4 | 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
5 | var defineProperty = (function() {
6 | // IE 8 only supports `Object.defineProperty` on DOM elements
7 | try {
8 | var object = {};
9 | var $defineProperty = Object.defineProperty;
10 | var result = $defineProperty(object, object, object) && $defineProperty;
11 | } catch(error) {}
12 | return result;
13 | }());
14 | var codePointAt = function(position) {
15 | if (this == null) {
16 | throw TypeError();
17 | }
18 | var string = String(this);
19 | var size = string.length;
20 | // `ToInteger`
21 | var index = position ? Number(position) : 0;
22 | if (index != index) { // better `isNaN`
23 | index = 0;
24 | }
25 | // Account for out-of-bounds indices:
26 | if (index < 0 || index >= size) {
27 | return undefined;
28 | }
29 | // Get the first code unit
30 | var first = string.charCodeAt(index);
31 | var second;
32 | if ( // check if it’s the start of a surrogate pair
33 | first >= 0xD800 && first <= 0xDBFF && // high surrogate
34 | size > index + 1 // there is a next code unit
35 | ) {
36 | second = string.charCodeAt(index + 1);
37 | if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
38 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
39 | return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
40 | }
41 | }
42 | return first;
43 | };
44 | if (defineProperty) {
45 | defineProperty(String.prototype, 'codePointAt', {
46 | 'value': codePointAt,
47 | 'configurable': true,
48 | 'writable': true
49 | });
50 | } else {
51 | String.prototype.codePointAt = codePointAt;
52 | }
53 | }());
54 | }
55 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/polyfills/fromcodepoint.js:
--------------------------------------------------------------------------------
1 | /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
2 | if (!String.fromCodePoint) {
3 | (function() {
4 | var defineProperty = (function() {
5 | // IE 8 only supports `Object.defineProperty` on DOM elements
6 | try {
7 | var object = {};
8 | var $defineProperty = Object.defineProperty;
9 | var result = $defineProperty(object, object, object) && $defineProperty;
10 | } catch(error) {}
11 | return result;
12 | }());
13 | var stringFromCharCode = String.fromCharCode;
14 | var floor = Math.floor;
15 | var fromCodePoint = function(_) {
16 | var MAX_SIZE = 0x4000;
17 | var codeUnits = [];
18 | var highSurrogate;
19 | var lowSurrogate;
20 | var index = -1;
21 | var length = arguments.length;
22 | if (!length) {
23 | return '';
24 | }
25 | var result = '';
26 | while (++index < length) {
27 | var codePoint = Number(arguments[index]);
28 | if (
29 | !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
30 | codePoint < 0 || // not a valid Unicode code point
31 | codePoint > 0x10FFFF || // not a valid Unicode code point
32 | floor(codePoint) != codePoint // not an integer
33 | ) {
34 | throw RangeError('Invalid code point: ' + codePoint);
35 | }
36 | if (codePoint <= 0xFFFF) { // BMP code point
37 | codeUnits.push(codePoint);
38 | } else { // Astral code point; split in surrogate halves
39 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
40 | codePoint -= 0x10000;
41 | highSurrogate = (codePoint >> 10) + 0xD800;
42 | lowSurrogate = (codePoint % 0x400) + 0xDC00;
43 | codeUnits.push(highSurrogate, lowSurrogate);
44 | }
45 | if (index + 1 == length || codeUnits.length > MAX_SIZE) {
46 | result += stringFromCharCode.apply(null, codeUnits);
47 | codeUnits.length = 0;
48 | }
49 | }
50 | return result;
51 | };
52 | if (defineProperty) {
53 | defineProperty(String, 'fromCodePoint', {
54 | 'value': fromCodePoint,
55 | 'configurable': true,
56 | 'writable': true
57 | });
58 | } else {
59 | String.fromCodePoint = fromCodePoint;
60 | }
61 | }());
62 | }
63 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/antlr4/tree/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 | * Use of this file is governed by the BSD 3-clause license that
3 | * can be found in the LICENSE.txt file in the project root.
4 | */
5 |
6 | var Tree = require('./Tree');
7 | exports.Trees = require('./Trees').Trees;
8 | exports.RuleNode = Tree.RuleNode;
9 | exports.ParseTreeListener = Tree.ParseTreeListener;
10 | exports.ParseTreeVisitor = Tree.ParseTreeVisitor;
11 | exports.ParseTreeWalker = Tree.ParseTreeWalker;
12 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/src/main/antlr/MiniCalcParser.g4:
--------------------------------------------------------------------------------
1 | parser grammar MiniCalcParser;
2 |
3 | options { tokenVocab=MiniCalcLexer; }
4 |
5 | miniCalcFile : lines=line+ ;
6 |
7 | line : statement (NEWLINE | EOF) ;
8 |
9 | statement : inputDeclaration # inputDeclarationStatement
10 | | varDeclaration # varDeclarationStatement
11 | | assignment # assignmentStatement
12 | | print # printStatement ;
13 |
14 | print : PRINT LPAREN expression RPAREN ;
15 |
16 | inputDeclaration : INPUT type name=ID ;
17 |
18 | varDeclaration : VAR assignment ;
19 |
20 | assignment : ID ASSIGN expression ;
21 |
22 | expression : left=expression operator=(DIVISION|ASTERISK) right=expression # binaryOperation
23 | | left=expression operator=(PLUS|MINUS) right=expression # binaryOperation
24 | | value=expression AS targetType=type # typeConversion
25 | | LPAREN expression RPAREN # parenExpression
26 | | ID # valueReference
27 | | MINUS expression # minusExpression
28 | | STRING_OPEN (parts+=stringLiteralContent)* STRING_CLOSE # stringLiteral
29 | | INTLIT # intLiteral
30 | | DECLIT # decimalLiteral ;
31 |
32 | stringLiteralContent : STRING_CONTENT # constantString
33 | | INTERPOLATION_OPEN expression INTERPOLATION_CLOSE # interpolatedValue ;
34 |
35 | type : INT # integer
36 | | DECIMAL # decimal
37 | | STRING # string ;
38 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/src/main/kotlin/UsingLexer.kt:
--------------------------------------------------------------------------------
1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream
2 | import org.antlr.v4.kotlinruntime.Token
3 |
4 | fun main(args: Array) {
5 |
6 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) {
7 | // throw RuntimeException("DIFFERENT LENGTHS")
8 | // }
9 | // for (i in 0..MiniCalcLexer.serializedATN.length) {
10 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) {
11 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}")
12 | // }
13 | // }
14 |
15 | val input = ANTLRInputStream("1 + 2")
16 | val lexer = MiniCalcLexer(input)
17 | var token : Token? = null
18 | do {
19 | token = lexer.nextToken()
20 | println("TOKEN $token")
21 |
22 | } while (token?.type != -1)
23 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/src/test/kotlin/MiniCalcLexerTest.kt:
--------------------------------------------------------------------------------
1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream
2 | import org.antlr.v4.kotlinruntime.atn.EmptyPredictionContext
3 | import org.antlr.v4.kotlinruntime.atn.PredictionContext
4 | import kotlin.test.*
5 |
6 | class TestingLexer {
7 |
8 | @Test fun firstTokenDebug1() {
9 | val input = ANTLRInputStream("1 + 2")
10 | val lexer = MiniCalcLexer(input)
11 | val interpreter = lexer.interpreter
12 | val result = interpreter!!.match(input, 0)
13 | assertEquals(11, result)
14 | }
15 |
16 | @Test fun checkMaxs() {
17 | assertEquals(2147483647, PredictionContext.EMPTY_RETURN_STATE)
18 | }
19 |
20 | @Test fun emptyPredictionContext() {
21 | assertEquals(true, EmptyPredictionContext().hasEmptyPath())
22 | assertEquals(true, EmptyPredictionContext().isEmpty)
23 | }
24 |
25 | @Test fun firstTokenDebug2() {
26 | val input = ANTLRInputStream("1 + 2")
27 | val lexer = MiniCalcLexer(input)
28 | val interpreter = lexer.interpreter
29 | val decisionToDFA = interpreter!!.decisionToDFA
30 | val mode = 0
31 | val dfa = decisionToDFA[mode]
32 | assertEquals(true, dfa!!.s0 != null)
33 | assertEquals(0, dfa!!.s0!!.stateNumber)
34 | }
35 |
36 | @Test fun firstToken() {
37 | val input = ANTLRInputStream("1 + 2")
38 | val lexer = MiniCalcLexer(input)
39 | val token = lexer.nextToken()
40 |
41 | assertEquals("1", token.text)
42 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, token.type)
43 | }
44 |
45 | @Test fun simpleTokens() {
46 | val input = ANTLRInputStream("1 + 2")
47 | val lexer = MiniCalcLexer(input)
48 | val tokens = lexer.allTokens
49 | assertEquals(5, tokens.size)
50 |
51 | var i = 0
52 | assertEquals("1", tokens[i].text)
53 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type)
54 |
55 | i++
56 | assertEquals(" ", tokens[i].text)
57 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type)
58 |
59 | i++
60 | assertEquals("+", tokens[i].text)
61 | assertEquals(MiniCalcLexer.Tokens.PLUS.id, tokens[i].type)
62 |
63 | i++
64 | assertEquals(" ", tokens[i].text)
65 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type)
66 |
67 | i++
68 | assertEquals("2", tokens[i].text)
69 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type)
70 | }
71 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-js/src/test/kotlin/MiscStringTest.kt:
--------------------------------------------------------------------------------
1 | import com.strumenta.kotlinmultiplatform.toCharArray
2 | import kotlin.test.*
3 |
4 | fun assertArrayEquals(a: CharArray, b: CharArray) {
5 | assertEquals(a.size, b.size)
6 | for (i in 0..a.size) {
7 | assertEquals(a[i], b[i])
8 | }
9 | }
10 |
11 | class MiscStringTest {
12 |
13 | @Test fun testToCharArrayEmpty() {
14 | assertArrayEquals(charArrayOf(), "".toCharArray())
15 | }
16 |
17 | @Test fun testToCharArrayEmptyLength() {
18 | assertEquals(0, "".toCharArray().size)
19 | }
20 |
21 | @Test fun testToCharArrayEmptyEl0() {
22 | assertEquals('a', "abc def".toCharArray()[0])
23 | }
24 |
25 | @Test fun testToCharArray() {
26 | assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray())
27 | }
28 |
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/.gitignore:
--------------------------------------------------------------------------------
1 | generated-src
2 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlin_version = '1.2.60'
3 | ext.projectVersion = '0.0.2'
4 | ext.antlrKotlinVersion = projectVersion
5 |
6 | repositories {
7 | mavenCentral()
8 | mavenLocal()
9 | }
10 | dependencies {
11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
12 | classpath "com.strumenta.antlr-kotlin:antlr-kotlin-gradle-plugin:$projectVersion"
13 | }
14 | }
15 |
16 | apply plugin: 'kotlin'
17 | apply plugin: 'idea'
18 | apply plugin: 'com.strumenta.antlrkotlin'
19 |
20 | repositories {
21 | mavenCentral()
22 | mavenLocal()
23 | }
24 |
25 | dependencies {
26 | compile "com.strumenta.antlr-kotlin:antlr-kotlin-runtime-common:$projectVersion"
27 | compile "com.strumenta.antlr-kotlin:antlr-kotlin-runtime-jvm:$projectVersion"
28 | compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
29 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
30 | //testCompile 'junit:junit:4.12'
31 | }
32 |
33 | generateKotlinGrammarSource {
34 | version = projectVersion
35 | maxHeapSize = "64m"
36 | arguments += ['-package', 'me.tomassetti.minicalc']
37 | outputDirectory = new File("generated-src/antlr/".toString())
38 | }
39 | compileKotlin.dependsOn generateKotlinGrammarSource
40 | sourceSets {
41 | generated {
42 | kotlin.srcDir 'generated-src/antlr/'
43 | }
44 | }
45 | compileKotlin.source sourceSets.generated.kotlin, sourceSets.main.kotlin
46 |
47 | clean{
48 | delete "generated-src"
49 | }
50 |
51 | idea {
52 | module {
53 | sourceDirs += file("generated-src/antlr/")
54 | }
55 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/main/antlr/MiniCalcParser.g4:
--------------------------------------------------------------------------------
1 | parser grammar MiniCalcParser;
2 |
3 | options { tokenVocab=MiniCalcLexer; }
4 |
5 | miniCalcFile : lines=line+ ;
6 |
7 | line : statement (NEWLINE | EOF) ;
8 |
9 | statement : inputDeclaration # inputDeclarationStatement
10 | | varDeclaration # varDeclarationStatement
11 | | assignment # assignmentStatement
12 | | print # printStatement ;
13 |
14 | print : PRINT LPAREN expression RPAREN ;
15 |
16 | inputDeclaration : INPUT type name=ID ;
17 |
18 | varDeclaration : VAR assignment ;
19 |
20 | assignment : ID ASSIGN expression ;
21 |
22 | expression : left=expression operator=(DIVISION|ASTERISK) right=expression # binaryOperation
23 | | left=expression operator=(PLUS|MINUS) right=expression # binaryOperation
24 | | value=expression AS targetType=type # typeConversion
25 | | LPAREN expression RPAREN # parenExpression
26 | | ID # valueReference
27 | | MINUS expression # minusExpression
28 | | STRING_OPEN (parts+=stringLiteralContent)* STRING_CLOSE # stringLiteral
29 | | INTLIT # intLiteral
30 | | DECLIT # decimalLiteral ;
31 |
32 | stringLiteralContent : STRING_CONTENT # constantString
33 | | INTERPOLATION_OPEN expression INTERPOLATION_CLOSE # interpolatedValue ;
34 |
35 | type : INT # integer
36 | | DECIMAL # decimal
37 | | STRING # string ;
38 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/main/java/MiniCalcLexer.tokens:
--------------------------------------------------------------------------------
1 | NEWLINE=1
2 | WS=2
3 | INPUT=3
4 | VAR=4
5 | PRINT=5
6 | AS=6
7 | INT=7
8 | DECIMAL=8
9 | STRING=9
10 | ID=10
11 | INTLIT=11
12 | DECLIT=12
13 | PLUS=13
14 | MINUS=14
15 | ASTERISK=15
16 | DIVISION=16
17 | ASSIGN=17
18 | LPAREN=18
19 | RPAREN=19
20 | STRING_OPEN=20
21 | UNMATCHED=21
22 | ESCAPE_STRING_DELIMITER=22
23 | ESCAPE_SLASH=23
24 | ESCAPE_NEWLINE=24
25 | ESCAPE_SHARP=25
26 | STRING_CLOSE=26
27 | INTERPOLATION_OPEN=27
28 | STRING_CONTENT=28
29 | INTERPOLATION_CLOSE=29
30 | 'input'=3
31 | 'var'=4
32 | 'print'=5
33 | '\\"'=22
34 | '\\\\'=23
35 | '\\n'=24
36 | '\\#'=25
37 | '#{'=27
38 | '}'=29
39 |
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/main/kotlin/UsingLexer.kt:
--------------------------------------------------------------------------------
1 |
2 | import org.antlr.v4.kotlinruntime.ANTLRInputStream
3 | import org.antlr.v4.kotlinruntime.CharStream
4 | import org.antlr.v4.kotlinruntime.Token
5 | import java.lang.RuntimeException
6 | import me.tomassetti.minicalc.MiniCalcLexer
7 |
8 | fun main(args: Array) {
9 |
10 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) {
11 | // throw RuntimeException("DIFFERENT LENGTHS")
12 | // }
13 | // for (i in 0..MiniCalcLexer.serializedATN.length) {
14 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) {
15 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}")
16 | // }
17 | // }
18 |
19 | val input = ANTLRInputStream("1 + 2")
20 | val lexer = MiniCalcLexer(input)
21 | var token : Token? = null
22 | do {
23 | token = lexer.nextToken()
24 | println("TOKEN $token")
25 |
26 | } while (token?.type != -1)
27 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/main/kotlin/UsingParser.kt:
--------------------------------------------------------------------------------
1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream
2 | import org.antlr.v4.kotlinruntime.CharStream
3 | import org.antlr.v4.kotlinruntime.CommonTokenStream
4 | import org.antlr.v4.kotlinruntime.Token
5 | import java.lang.RuntimeException
6 | import me.tomassetti.minicalc.MiniCalcLexer
7 | import me.tomassetti.minicalc.MiniCalcParser
8 |
9 | fun main(args: Array) {
10 |
11 | // if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) {
12 | // throw RuntimeException("DIFFERENT LENGTHS")
13 | // }
14 | // for (i in 0..MiniCalcLexer.serializedATN.length) {
15 | // if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) {
16 | // throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}")
17 | // }
18 | // }
19 |
20 | val input = ANTLRInputStream("input Int width\n")
21 | val lexer = MiniCalcLexer(input)
22 | var parser = MiniCalcParser(CommonTokenStream(lexer))
23 | try {
24 | val root = parser.miniCalcFile()
25 | println("Parsed: ${root.javaClass}")
26 | println("Parsed: ${root.childCount}")
27 | println("Parsed: ${root.children!![0].javaClass}")
28 | } catch (e : Throwable) {
29 | println("Error: $e")
30 | }
31 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/test/kotlin/MiniCalcLexerTest.kt:
--------------------------------------------------------------------------------
1 | import org.antlr.v4.kotlinruntime.ANTLRInputStream
2 | import org.antlr.v4.kotlinruntime.atn.EmptyPredictionContext
3 | import org.antlr.v4.kotlinruntime.atn.PredictionContext
4 | import kotlin.test.*
5 | import me.tomassetti.minicalc.MiniCalcLexer
6 |
7 | class TestingLexer {
8 |
9 | @Test fun firstTokenDebug1() {
10 | val input = ANTLRInputStream("1 + 2")
11 | val lexer = MiniCalcLexer(input)
12 | val interpreter = lexer.interpreter
13 | val result = interpreter!!.match(input, 0)
14 | assertEquals(11, result)
15 | }
16 |
17 | @Test fun checkMaxs() {
18 | assertEquals(2147483647, PredictionContext.EMPTY_RETURN_STATE)
19 | }
20 |
21 | @Test fun emptyPredictionContext() {
22 | assertEquals(true, EmptyPredictionContext().hasEmptyPath())
23 | assertEquals(true, EmptyPredictionContext().isEmpty)
24 | }
25 |
26 | @Test fun firstTokenDebug2() {
27 | val input = ANTLRInputStream("1 + 2")
28 | val lexer = MiniCalcLexer(input)
29 | val interpreter = lexer.interpreter
30 | val decisionToDFA = interpreter!!.decisionToDFA
31 | val mode = 0
32 | val dfa = decisionToDFA[mode]
33 | assertEquals(true, dfa!!.s0 != null)
34 | assertEquals(0, dfa!!.s0!!.stateNumber)
35 | }
36 |
37 | @Test fun firstToken() {
38 | val input = ANTLRInputStream("1 + 2")
39 | val lexer = MiniCalcLexer(input)
40 | val token = lexer.nextToken()
41 |
42 | assertEquals("1", token.text)
43 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, token.type)
44 | }
45 |
46 | @Test fun simpleTokens() {
47 | val input = ANTLRInputStream("1 + 2")
48 | val lexer = MiniCalcLexer(input)
49 | val tokens = lexer.allTokens
50 | assertEquals(5, tokens.size)
51 |
52 | var i = 0
53 | assertEquals("1", tokens[i].text)
54 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type)
55 |
56 | i++
57 | assertEquals(" ", tokens[i].text)
58 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type)
59 |
60 | i++
61 | assertEquals("+", tokens[i].text)
62 | assertEquals(MiniCalcLexer.Tokens.PLUS.id, tokens[i].type)
63 |
64 | i++
65 | assertEquals(" ", tokens[i].text)
66 | assertEquals(MiniCalcLexer.Tokens.WS.id, tokens[i].type)
67 |
68 | i++
69 | assertEquals("2", tokens[i].text)
70 | assertEquals(MiniCalcLexer.Tokens.INTLIT.id, tokens[i].type)
71 | }
72 | }
--------------------------------------------------------------------------------
/antlr-kotlin-examples-jvm/src/test/kotlin/MiscStringTest.kt:
--------------------------------------------------------------------------------
1 | import com.strumenta.kotlinmultiplatform.toCharArray
2 | import kotlin.test.*
3 |
4 | fun assertArrayEquals(a: CharArray, b: CharArray) {
5 | assertEquals(a.size, b.size)
6 | for (i in 0..a.size) {
7 | assertEquals(a[i], b[i])
8 | }
9 | }
10 |
11 | class MiscStringTest {
12 |
13 | // @Test fun testToCharArrayEmpty() {
14 | // assertArrayEquals(charArrayOf(), "".toCharArray())
15 | // }
16 |
17 | @Test fun testToCharArrayEmptyLength() {
18 | assertEquals(0, "".toCharArray().size)
19 | }
20 |
21 | @Test fun testToCharArrayEmptyEl0() {
22 | assertEquals('a', "abc def".toCharArray()[0])
23 | }
24 |
25 | // @Test fun testToCharArray() {
26 | // assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray())
27 | // }
28 |
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlinVersion = kotlinVersion
3 |
4 | repositories {
5 | mavenCentral()
6 | maven {
7 | url "https://plugins.gradle.org/m2/"
8 | }
9 | }
10 | dependencies {
11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
12 | }
13 | }
14 |
15 | apply plugin: 'org.jetbrains.kotlin.jvm'
16 | apply plugin: 'java-gradle-plugin'
17 | apply plugin: 'maven'
18 |
19 | group = projectGroup
20 | version = projectVersion
21 |
22 | repositories {
23 | jcenter()
24 | mavenLocal()
25 | }
26 |
27 | dependencies {
28 | compileOnly gradleApi()
29 | compileOnly "org.antlr:antlr4:${antlrVersion}@jar"
30 | compileOnly project(':antlr-kotlin-target')
31 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
32 | }
33 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/AntlrSourceVirtualDirectory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin;
18 |
19 | import groovy.lang.Closure;
20 | import org.gradle.api.Action;
21 | import org.gradle.api.file.SourceDirectorySet;
22 |
23 | /**
24 | * Contract for a Gradle "convention object" that acts as a handler for what I call a virtual directory mapping,
25 | * injecting a virtual directory named 'antlr' into the project's various {@link org.gradle.api.tasks.SourceSet source
26 | * sets}.
27 | */
28 | public interface AntlrSourceVirtualDirectory {
29 | String NAME = "antlr";
30 |
31 | /**
32 | * All Antlr source for this source set.
33 | *
34 | * @return The Antlr source. Never returns null.
35 | */
36 | SourceDirectorySet getAntlr();
37 |
38 | /**
39 | * Configures the Antlr source for this set. The given closure is used to configure the {@link org.gradle.api.file.SourceDirectorySet} (see
40 | * {@link #getAntlr}) which contains the Antlr source.
41 | *
42 | * @param configureClosure The closure to use to configure the Antlr source.
43 | * @return this
44 | */
45 | AntlrSourceVirtualDirectory antlr(Closure configureClosure);
46 |
47 | /**
48 | * Configures the Antlr source for this set. The given action is used to configure the {@link org.gradle.api.file.SourceDirectorySet} (see
49 | * {@link #getAntlr}) which contains the Antlr source.
50 | *
51 | * @param configureAction The action to use to configure the Antlr source.
52 | * @return this
53 | * @since 3.5
54 | */
55 | AntlrSourceVirtualDirectory antlr(Action super SourceDirectorySet> configureAction);
56 | }
57 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin.internal;
18 |
19 | import java.io.Serializable;
20 |
21 | public class AntlrResult implements Serializable {
22 |
23 | private final int errorCount;
24 | private final Exception exception;
25 |
26 | public AntlrResult(int errorCount) {
27 | this(errorCount, null);
28 | }
29 | public AntlrResult(int errorCount, Exception exception) {
30 | this.errorCount = errorCount;
31 | this.exception = exception;
32 | }
33 |
34 | public int getErrorCount() {
35 | return errorCount;
36 | }
37 |
38 | public Exception getException() {
39 | return exception;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSourceGenerationException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin.internal;
18 |
19 | import org.gradle.api.GradleException;
20 | import org.gradle.internal.exceptions.Contextual;
21 |
22 | @Contextual
23 | public class AntlrSourceGenerationException extends GradleException {
24 | public AntlrSourceGenerationException(String message, Throwable cause) {
25 | super(message, cause);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSourceVirtualDirectoryImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.strumenta.antlrkotlin.gradleplugin.internal;
17 |
18 | import groovy.lang.Closure;
19 | import org.gradle.api.Action;
20 | import org.gradle.api.file.SourceDirectorySet;
21 | import org.gradle.api.internal.file.SourceDirectorySetFactory;
22 | import org.gradle.api.plugins.antlr.AntlrSourceVirtualDirectory;
23 | import org.gradle.util.ConfigureUtil;
24 |
25 | /**
26 | * The implementation of the {@link org.gradle.api.plugins.antlr.AntlrSourceVirtualDirectory} contract.
27 | */
28 | public class AntlrSourceVirtualDirectoryImpl implements AntlrSourceVirtualDirectory {
29 | private final SourceDirectorySet antlr;
30 |
31 | public AntlrSourceVirtualDirectoryImpl(String parentDisplayName, SourceDirectorySetFactory sourceDirectorySetFactory) {
32 | final String displayName = parentDisplayName + " Antlr source";
33 | antlr = sourceDirectorySetFactory.create(displayName);
34 | antlr.getFilter().include("**/*.g");
35 | antlr.getFilter().include("**/*.g4");
36 | }
37 |
38 | @Override
39 | public SourceDirectorySet getAntlr() {
40 | return antlr;
41 | }
42 |
43 | @Override
44 | public AntlrSourceVirtualDirectory antlr(Closure configureClosure) {
45 | ConfigureUtil.configure(configureClosure, getAntlr());
46 | return this;
47 | }
48 |
49 | @Override
50 | public AntlrSourceVirtualDirectory antlr(Action super SourceDirectorySet> configureAction) {
51 | configureAction.execute(getAntlr());
52 | return this;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSpec.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin.internal;
18 |
19 | import java.io.File;
20 | import java.io.Serializable;
21 | import java.util.LinkedList;
22 | import java.util.List;
23 | import java.util.Set;
24 |
25 | public class AntlrSpec implements Serializable {
26 |
27 | private List arguments;
28 | private Set inputDirectories;
29 | private Set grammarFiles;
30 | private String maxHeapSize;
31 | private File outputDirectory;
32 |
33 | public AntlrSpec(List arguments, Set grammarFiles, Set inputDirectories, File outputDirectory, String maxHeapSize) {
34 | this.arguments = arguments;
35 | this.inputDirectories = inputDirectories;
36 | this.grammarFiles = grammarFiles;
37 | this.outputDirectory = outputDirectory;
38 | this.maxHeapSize = maxHeapSize;
39 | }
40 |
41 | public List getArguments() {
42 | return arguments;
43 | }
44 |
45 | public Set getGrammarFiles() {
46 | return grammarFiles;
47 | }
48 |
49 | public String getMaxHeapSize() {
50 | return maxHeapSize;
51 | }
52 |
53 | public File getOutputDirectory() {
54 | return outputDirectory;
55 | }
56 |
57 | public List asArgumentsWithFiles() {
58 | List commandLine = new LinkedList<>(arguments);
59 | commandLine.add("-o");
60 | commandLine.add(getOutputDirectory().getAbsolutePath());
61 | for (File file : getGrammarFiles()) {
62 | commandLine.add(file.getAbsolutePath());
63 | }
64 |
65 | return commandLine;
66 | }
67 |
68 | public Set getInputDirectories() {
69 | return inputDirectories;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrSpecFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin.internal;
18 |
19 | import org.gradle.api.file.SourceDirectorySet;
20 | import com.strumenta.antlrkotlin.gradleplugin.AntlrKotlinTask;
21 |
22 | import java.io.File;
23 | import java.util.LinkedList;
24 | import java.util.List;
25 | import java.util.Set;
26 |
27 | public class AntlrSpecFactory {
28 |
29 | public AntlrSpec create(AntlrKotlinTask antlrTask, Set grammarFiles,
30 | SourceDirectorySet sourceDirectorySet) {
31 | List arguments = new LinkedList<>(antlrTask.getArguments());
32 |
33 | if (antlrTask.isTrace() && !arguments.contains("-trace")) {
34 | arguments.add("-trace");
35 | }
36 | if (antlrTask.isTraceLexer() && !arguments.contains("-traceLexer")) {
37 | arguments.add("-traceLexer");
38 | }
39 | if (antlrTask.isTraceParser() && !arguments.contains("-traceParser")) {
40 | arguments.add("-traceParser");
41 | }
42 | if (antlrTask.isTraceTreeWalker() && !arguments.contains("-traceTreeWalker")) {
43 | arguments.add("-traceTreeWalker");
44 | }
45 |
46 | return new AntlrSpec(arguments, grammarFiles, sourceDirectorySet.getSrcDirs(), antlrTask.getOutputDirectory(),
47 | antlrTask.getMaxHeapSize());
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/internal/AntlrWorker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.strumenta.antlrkotlin.gradleplugin.internal;
18 |
19 | public interface AntlrWorker {
20 | AntlrResult runAntlr(AntlrSpec spec);
21 | }
22 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/java/com/strumenta/antlrkotlin/gradleplugin/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * A {@link org.gradle.api.Plugin} for generating parsers from Antlr grammars using the Kotlin target.
19 | */
20 | package com.strumenta.antlrkotlin.gradleplugin;
21 |
--------------------------------------------------------------------------------
/antlr-kotlin-gradle-plugin/src/main/resources/META-INF/gradle-plugins/com.strumenta.antlrkotlin.properties:
--------------------------------------------------------------------------------
1 | implementation-class=com.strumenta.antlrkotlin.gradleplugin.AntlrKotlinPlugin
2 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlinVersion = kotlinVersion
3 |
4 | repositories {
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
9 | }
10 | }
11 |
12 | apply plugin: 'kotlin-platform-common'
13 | apply plugin: 'maven'
14 |
15 | repositories {
16 | mavenCentral()
17 | }
18 |
19 | group = projectGroup
20 | version = projectVersion
21 |
22 | dependencies {
23 | compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion"
24 | testCompile "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlinVersion"
25 | testCompile "org.jetbrains.kotlin:kotlin-test-common:$kotlinVersion"
26 | testCompile "junit:junit:4.12"
27 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion"
28 | }
29 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ANTLRFileStream.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | import org.antlr.v4.kotlinruntime.misc.Utils
9 |
10 | ///**
11 | // * This is an [ANTLRInputStream] that is loaded from a file all at once
12 | // * when you construct the object.
13 | // *
14 | // */
15 | //@Deprecated("as of 4.7 Please use {@link CharStreams} interface.")
16 | //class ANTLRFileStream constructor(fileName: String, encoding: String? = null) : ANTLRInputStream() {
17 | // override var sourceName: String
18 | // protected set
19 | //
20 | // init {
21 | // this.sourceName = fileName
22 | // load(fileName, encoding)
23 | // }
24 | //
25 | // fun load(fileName: String, encoding: String?) {
26 | // data = Utils.readFile(fileName, encoding)
27 | // this.n = data.size
28 | // }
29 | //}
30 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/BaseErrorListener.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | import com.strumenta.kotlinmultiplatform.BitSet
9 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet
10 | import org.antlr.v4.kotlinruntime.dfa.DFA
11 |
12 | /**
13 | * Provides an empty default implementation of [ANTLRErrorListener]. The
14 | * default implementation of each method does nothing, but can be overridden as
15 | * necessary.
16 | *
17 | * @author Sam Harwell
18 | */
19 | open class BaseErrorListener : ANTLRErrorListener {
20 | override fun syntaxError(recognizer: Recognizer<*, *>,
21 | offendingSymbol: Any?,
22 | line: Int,
23 | charPositionInLine: Int,
24 | msg: String,
25 | e: RecognitionException?) {
26 | }
27 |
28 | override fun reportAmbiguity(recognizer: Parser,
29 | dfa: DFA,
30 | startIndex: Int,
31 | stopIndex: Int,
32 | exact: Boolean,
33 | ambigAlts: BitSet,
34 | configs: ATNConfigSet) {
35 | }
36 |
37 | override fun reportAttemptingFullContext(recognizer: Parser,
38 | dfa: DFA,
39 | startIndex: Int,
40 | stopIndex: Int,
41 | conflictingAlts: BitSet,
42 | configs: ATNConfigSet) {
43 | }
44 |
45 | override fun reportContextSensitivity(recognizer: Parser,
46 | dfa: DFA,
47 | startIndex: Int,
48 | stopIndex: Int,
49 | prediction: Int,
50 | configs: ATNConfigSet) {
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/CharStream.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime
8 |
9 | import org.antlr.v4.kotlinruntime.misc.Interval
10 |
11 | /** A source of characters for an ANTLR lexer. */
12 | interface CharStream : IntStream {
13 | /**
14 | * This method returns the text for a range of characters within this input
15 | * stream. This method is guaranteed to not throw an exception if the
16 | * specified `interval` lies entirely within a marked range. For more
17 | * information about marked ranges, see [IntStream.mark].
18 | *
19 | * @param interval an interval within the stream
20 | * @return the text of the specified interval
21 | *
22 | * @throws NullPointerException if `interval` is `null`
23 | * @throws IllegalArgumentException if `interval.a < 0`, or if
24 | * `interval.b < interval.a - 1`, or if `interval.b` lies at or
25 | * past the end of the stream
26 | * @throws UnsupportedOperationException if the stream does not support
27 | * getting the text of the specified interval
28 | */
29 | fun getText(interval: Interval): String
30 |
31 | companion object {
32 | val EOF = IntStream.EOF
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ConsoleErrorListener.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | import com.strumenta.kotlinmultiplatform.errMessage
9 |
10 | /**
11 | *
12 | * @author Sam Harwell
13 | */
14 | class ConsoleErrorListener : BaseErrorListener() {
15 |
16 | /**
17 | * {@inheritDoc}
18 | *
19 | *
20 | *
21 | * This implementation prints messages to [System.err] containing the
22 | * values of `line`, `charPositionInLine`, and `msg` using
23 | * the following format.
24 | *
25 | *
26 | * line *line*:*charPositionInLine* *msg*
27 |
*
28 | */
29 | override fun syntaxError(recognizer: Recognizer<*, *>,
30 | offendingSymbol: Any?,
31 | line: Int,
32 | charPositionInLine: Int,
33 | msg: String,
34 | e: RecognitionException?) {
35 | errMessage("line $line:$charPositionInLine $msg")
36 | }
37 |
38 | companion object {
39 | /**
40 | * Provides a default instance of [ConsoleErrorListener].
41 | */
42 | val INSTANCE = ConsoleErrorListener()
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/FailedPredicateException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | import org.antlr.v4.kotlinruntime.atn.AbstractPredicateTransition
9 | import org.antlr.v4.kotlinruntime.atn.PredicateTransition
10 |
11 |
12 | private fun formatMessage(predicate: String?, message: String?): String {
13 | return message ?: "failed predicate: {$predicate}?"
14 |
15 | }
16 |
17 | /** A semantic predicate failed during validation. Validation of predicates
18 | * occurs when normally parsing the alternative just like matching a token.
19 | * Disambiguating predicate evaluation occurs when we test a predicate during
20 | * prediction.
21 | */
22 | class FailedPredicateException constructor(recognizer: Parser,
23 | val predicate: String? = null,
24 | message: String? = null) : RecognitionException(recognizer, recognizer.readInputStream()!!, recognizer.context!!, formatMessage(predicate, message)) {
25 | var ruleIndex: Int = -1
26 | var predIndex: Int = -1
27 |
28 | init {
29 | val s = recognizer.interpreter!!.atn.states.get(recognizer.state)
30 |
31 | val trans = s!!.transition(0) as AbstractPredicateTransition
32 | if (trans is PredicateTransition) {
33 | this.ruleIndex = (trans as PredicateTransition).ruleIndex
34 | this.predIndex = (trans as PredicateTransition).predIndex
35 | } else {
36 | this.ruleIndex = 0
37 | this.predIndex = 0
38 | }
39 | TODO()
40 | //this.offendingToken = recognizer.currentToken
41 | }
42 |
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/InputMismatchException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | /** This signifies any kind of mismatched input exceptions such as
9 | * when the current input does not match the expected token.
10 | */
11 | class InputMismatchException : RecognitionException {
12 | constructor(recognizer: Parser) : super(recognizer, recognizer.readInputStream()!!, recognizer.context!!) {
13 | this.offendingToken = recognizer.currentToken
14 | }
15 |
16 | constructor(recognizer: Parser, state: Int, ctx: ParserRuleContext) : super(recognizer, recognizer.readInputStream()!!, ctx) {
17 | this.offendingState = state
18 | this.offendingToken = recognizer.currentToken
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/InterpreterRuleContext.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | /**
9 | * This class extends [ParserRuleContext] by allowing the value of
10 | * [.getRuleIndex] to be explicitly set for the context.
11 | *
12 | *
13 | *
14 | * [ParserRuleContext] does not include field storage for the rule index
15 | * since the context classes created by the code generator override the
16 | * [.getRuleIndex] method to return the correct value for that context.
17 | * Since the parser interpreter does not use the context classes generated for a
18 | * parser, this class (with slightly more memory overhead per node) is used to
19 | * provide equivalent functionality.
20 | */
21 | class InterpreterRuleContext : ParserRuleContext {
22 | /** This is the backing field for [.getRuleIndex]. */
23 | override var ruleIndex = -1
24 | set(value: Int) {
25 | super.ruleIndex = value
26 | }
27 |
28 | constructor() {}
29 |
30 | /**
31 | * Constructs a new [InterpreterRuleContext] with the specified
32 | * parent, invoking state, and rule index.
33 | *
34 | * @param parent The parent context.
35 | * @param invokingStateNumber The invoking state number.
36 | * @param ruleIndex The rule index for the current context.
37 | */
38 | constructor(parent: ParserRuleContext,
39 | invokingStateNumber: Int,
40 | ruleIndex: Int) : super(parent, invokingStateNumber) {
41 | this.ruleIndex = ruleIndex
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/LexerNoViableAltException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime
8 |
9 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet
10 | import org.antlr.v4.kotlinruntime.misc.Interval
11 | import org.antlr.v4.kotlinruntime.misc.Utils
12 |
13 | class LexerNoViableAltException(lexer: Lexer,
14 | input: CharStream,
15 | /** Matching attempted at what input index? */
16 | val startIndex: Int,
17 | /** Which configurations did we try at input.index() that couldn't match input.LA(1)? */
18 | val deadEndConfigs: ATNConfigSet) : RecognitionException(lexer, input, null) {
19 |
20 | override val inputStream: CharStream
21 | get() = super.inputStream as CharStream
22 |
23 | override fun toString(): String {
24 | var symbol = ""
25 | if (startIndex >= 0 && startIndex < inputStream.size()) {
26 | symbol = inputStream.getText(Interval.of(startIndex, startIndex))
27 | symbol = Utils.escapeWhitespace(symbol, false)
28 | }
29 |
30 | return "LexerNoViableAltException('$symbol')"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/NoViableAltException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime
7 |
8 | import org.antlr.v4.kotlinruntime.atn.ATNConfigSet
9 |
10 | /** Indicates that the parser could not decide which of two or more paths
11 | * to take based upon the remaining input. It tracks the starting token
12 | * of the offending input and also knows where the parser was
13 | * in the various paths when the error. Reported by reportNoViableAlternative()
14 | */
15 | class NoViableAltException constructor(recognizer: Parser,
16 | input: TokenStream? = recognizer.readInputStream() as TokenStream?,
17 | /** The token object at the start index; the input stream might
18 | * not be buffering tokens so get a reference to it. (At the
19 | * time the error occurred, of course the stream needs to keep a
20 | * buffer all of the tokens but later we might not have access to those.)
21 | */
22 |
23 | val startToken: Token? = recognizer.currentToken,
24 | offendingToken: Token? = recognizer.currentToken,
25 | /** Which configurations did we try at input.index() that couldn't match input.LT(1)? */
26 |
27 | val deadEndConfigs: ATNConfigSet? = null,
28 | ctx: ParserRuleContext? = recognizer.context) : RecognitionException(recognizer, input!!, ctx!!) {
29 |
30 | init {
31 | this.offendingToken = offendingToken
32 | }
33 |
34 | }// LL(1) error
35 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/RuleContextWithAltNum.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime
8 |
9 | import org.antlr.v4.kotlinruntime.atn.ATN
10 |
11 | /** A handy class for use with
12 | *
13 | * options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;}
14 | *
15 | * that provides a backing field / impl for the outer alternative number
16 | * matched for an internal parse tree node.
17 | *
18 | * I'm only putting into Java runtime as I'm certain I'm the only one that
19 | * will really every use this.
20 | */
21 | class RuleContextWithAltNum : ParserRuleContext {
22 | override var altNumber: Int = 0
23 |
24 | constructor() {
25 | altNumber = ATN.INVALID_ALT_NUMBER
26 | }
27 |
28 | constructor(parent: ParserRuleContext, invokingStateNumber: Int) : super(parent, invokingStateNumber) {}
29 | }
30 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/TokenFactory.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime
8 |
9 | import org.antlr.v4.kotlinruntime.misc.Pair
10 |
11 | /** The default mechanism for creating tokens. It's used by default in Lexer and
12 | * the error handling strategy (to create missing tokens). Notifying the parser
13 | * of a new factory means that it notifies its token source and error strategy.
14 | */
15 | interface TokenFactory {
16 | /** This is the method used to create tokens in the lexer and in the
17 | * error handling strategy. If text!=null, than the start and stop positions
18 | * are wiped to -1 in the text override is set in the CommonToken.
19 | */
20 | fun create(source: Pair, type: Int, text: String?,
21 | channel: Int, start: Int, stop: Int,
22 | line: Int, charPositionInLine: Int): Symbol
23 |
24 | /** Generically useful */
25 | fun create(type: Int, text: String): Symbol
26 | }
27 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/WritableToken.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime
8 |
9 | interface WritableToken : Token {
10 |
11 | override var text: String?
12 |
13 |
14 | /** Get the token type of the token */
15 | override var type: Int
16 |
17 | /** The line number on which the 1st character of this token was matched,
18 | * line=1..n
19 | */
20 | override var line: Int
21 |
22 | /** The index of the first character of this token relative to the
23 | * beginning of the line at which it occurs, 0..n-1
24 | */
25 | override var charPositionInLine: Int
26 |
27 | /** Return the channel this token. Each token can arrive at the parser
28 | * on a different channel, but the parser only "tunes" to a single channel.
29 | * The parser ignores everything not on DEFAULT_CHANNEL.
30 | */
31 | override var channel: Int
32 |
33 | /** An index from 0..n-1 of the token object in the input stream.
34 | * This must be valid in order to print token streams and
35 | * use TokenRewriteStream.
36 | *
37 | * Return -1 to indicate that this token was conjured up since
38 | * it doesn't have a valid index.
39 | */
40 | override var tokenIndex: Int
41 | }
42 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/ast/Node.kt:
--------------------------------------------------------------------------------
1 | package org.antlr.v4.kotlinruntime.ast
2 |
3 | /**
4 | * The Abstract Syntax Tree will be constituted by instances of Node.
5 | */
6 | interface Node {
7 | val parent: Node?
8 | val position: Position?
9 | }
10 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ATNDeserializationOptions.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | *
11 | * @author Sam Harwell
12 | */
13 | class ATNDeserializationOptions {
14 |
15 | var isReadOnly: Boolean = false
16 | private set
17 | private var verifyATN: Boolean = false
18 | private var generateRuleBypassTransitions: Boolean = false
19 |
20 | var isVerifyATN: Boolean
21 | get() = verifyATN
22 | set(verifyATN) {
23 | throwIfReadOnly()
24 | this.verifyATN = verifyATN
25 | }
26 |
27 | var isGenerateRuleBypassTransitions: Boolean
28 | get() = generateRuleBypassTransitions
29 | set(generateRuleBypassTransitions) {
30 | throwIfReadOnly()
31 | this.generateRuleBypassTransitions = generateRuleBypassTransitions
32 | }
33 |
34 | constructor() {
35 | this.verifyATN = true
36 | this.generateRuleBypassTransitions = false
37 | }
38 |
39 | constructor(options: ATNDeserializationOptions) {
40 | this.verifyATN = options.verifyATN
41 | this.generateRuleBypassTransitions = options.generateRuleBypassTransitions
42 | }
43 |
44 | fun makeReadOnly() {
45 | isReadOnly = true
46 | }
47 |
48 | protected fun throwIfReadOnly() {
49 | if (isReadOnly) {
50 | throw IllegalStateException("The object is read only.")
51 | }
52 | }
53 |
54 | companion object {
55 | val defaultOptions: ATNDeserializationOptions
56 |
57 | init {
58 | defaultOptions = ATNDeserializationOptions()
59 | defaultOptions.makeReadOnly()
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ATNType.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | * Represents the type of recognizer an ATN applies to.
11 | *
12 | * @author Sam Harwell
13 | */
14 | enum class ATNType {
15 |
16 | /**
17 | * A lexer grammar.
18 | */
19 | LEXER,
20 |
21 | /**
22 | * A parser grammar.
23 | */
24 | PARSER
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/AbstractPredicateTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | *
11 | * @author Sam Harwell
12 | */
13 | abstract class AbstractPredicateTransition(target: ATNState) : Transition(target)
14 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ActionTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class ActionTransition constructor(target: ATNState, val ruleIndex: Int, val actionIndex: Int = -1, val isCtxDependent: Boolean = false // e.g., $i ref in action
10 | ) : Transition(target) {
11 |
12 | override val serializationType: Int
13 | get() = Transition.ACTION
14 |
15 | override// we are to be ignored by analysis 'cept for predicates
16 | val isEpsilon: Boolean
17 | get() = true
18 |
19 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
20 | return false
21 | }
22 |
23 | override fun toString(): String {
24 | return "action_$ruleIndex:$actionIndex"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/AtomTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet
10 |
11 | /** TODO: make all transitions sets? no, should remove set edges */
12 | class AtomTransition(target: ATNState,
13 | /** The token type or character value; or, signifies special accessLabel. */
14 | val label: Int) : Transition(target) {
15 |
16 | override val serializationType: Int
17 | get() = Transition.ATOM
18 |
19 | override fun accessLabel(): IntervalSet? {
20 | return IntervalSet.of(label)
21 | }
22 |
23 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
24 | return label == symbol
25 | }
26 |
27 | override fun toString(): String {
28 | return label.toString()
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BasicBlockStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | *
11 | * @author Sam Harwell
12 | */
13 | class BasicBlockStartState : BlockStartState() {
14 | override val stateType: Int
15 | get() = ATNState.BLOCK_START
16 | }
17 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BasicState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | *
11 | * @author Sam Harwell
12 | */
13 | class BasicState : ATNState() {
14 |
15 | override val stateType: Int
16 | get() = ATNState.BASIC
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BlockEndState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** Terminal node of a simple `(a|b|c)` block. */
10 | class BlockEndState : ATNState() {
11 | var startState: BlockStartState? = null
12 |
13 | override val stateType: Int
14 | get() = ATNState.BLOCK_END
15 | }
16 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/BlockStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** The start of a regular `(...)` block. */
10 | abstract class BlockStartState : DecisionState() {
11 | var endState: BlockEndState? = null
12 | }
13 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/CodePointTransitions.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import com.strumenta.kotlinmultiplatform.isSupplementaryCodePoint
10 | import org.antlr.v4.kotlinruntime.misc.IntervalSet
11 |
12 | /**
13 | * Utility class to create [AtomTransition], [RangeTransition],
14 | * and [SetTransition] appropriately based on the range of the input.
15 | *
16 | * To keep the serialized ATN size small, we only inline atom and
17 | * range transitions for Unicode code points <= U+FFFF.
18 | *
19 | * Whenever we encounter a Unicode code point > U+FFFF, we represent that
20 | * as a set transition (even if it is logically an atom or a range).
21 | */
22 | object CodePointTransitions {
23 | /**
24 | * If `codePoint` is <= U+FFFF, returns a new [AtomTransition].
25 | * Otherwise, returns a new [SetTransition].
26 | */
27 | fun createWithCodePoint(target: ATNState, codePoint: Int): Transition {
28 | return if (Char.isSupplementaryCodePoint(codePoint)) {
29 | SetTransition(target, IntervalSet.of(codePoint))
30 | } else {
31 | AtomTransition(target, codePoint)
32 | }
33 | }
34 |
35 | /**
36 | * If `codePointFrom` and `codePointTo` are both
37 | * <= U+FFFF, returns a new [RangeTransition].
38 | * Otherwise, returns a new [SetTransition].
39 | */
40 | fun createWithCodePointRange(
41 | target: ATNState,
42 | codePointFrom: Int,
43 | codePointTo: Int): Transition {
44 | return if (Char.isSupplementaryCodePoint(codePointFrom) || Char.isSupplementaryCodePoint(codePointTo)) {
45 | SetTransition(target, IntervalSet.of(codePointFrom, codePointTo))
46 | } else {
47 | RangeTransition(target, codePointFrom, codePointTo)
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ContextSensitivityInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.ANTLRErrorListener
10 | import org.antlr.v4.kotlinruntime.TokenStream
11 |
12 | /**
13 | * This class represents profiling event information for a context sensitivity.
14 | * Context sensitivities are decisions where a particular input resulted in an
15 | * SLL conflict, but LL prediction produced a single unique alternative.
16 | *
17 | *
18 | *
19 | * In some cases, the unique alternative identified by LL prediction is not
20 | * equal to the minimum represented alternative in the conflicting SLL
21 | * configuration set. Grammars and inputs which result in this scenario are
22 | * unable to use [PredictionMode.SLL], which in turn means they cannot use
23 | * the two-stage parsing strategy to improve parsing performance for that
24 | * input.
25 | *
26 | * @see ParserATNSimulator.reportContextSensitivity
27 | *
28 | * @see ANTLRErrorListener.reportContextSensitivity
29 | *
30 | *
31 | * @since 4.3
32 | */
33 | class ContextSensitivityInfo
34 | /**
35 | * Constructs a new instance of the [ContextSensitivityInfo] class
36 | * with the specified detailed context sensitivity information.
37 | *
38 | * @param decision The decision number
39 | * @param configs The final configuration set containing the unique
40 | * alternative identified by full-context prediction
41 | * @param input The input token stream
42 | * @param startIndex The start index for the current prediction
43 | * @param stopIndex The index at which the context sensitivity was
44 | * identified during full-context prediction
45 | */
46 | (decision: Int,
47 | configs: ATNConfigSet,
48 | input: TokenStream, startIndex: Int, stopIndex: Int) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, true)
49 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/DecisionEventInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.TokenStream
10 |
11 | /**
12 | * This is the base class for gathering detailed information about prediction
13 | * events which occur during parsing.
14 | *
15 | * Note that we could record the parser call stack at the time this event
16 | * occurred but in the presence of left recursive rules, the stack is kind of
17 | * meaningless. It's better to look at the individual configurations for their
18 | * individual stacks. Of course that is a [PredictionContext] object
19 | * not a parse tree node and so it does not have information about the extent
20 | * (start...stop) of the various subtrees. Examining the stack tops of all
21 | * configurations provide the return states for the rule invocations.
22 | * From there you can get the enclosing rule.
23 | *
24 | * @since 4.3
25 | */
26 | open class DecisionEventInfo(
27 | /**
28 | * The invoked decision number which this event is related to.
29 | *
30 | * @see ATN.decisionToState
31 | */
32 | val decision: Int,
33 | /**
34 | * The configuration set containing additional information relevant to the
35 | * prediction state when the current event occurred, or `null` if no
36 | * additional information is relevant or available.
37 | */
38 | val configs: ATNConfigSet,
39 | /**
40 | * The input token stream which is being parsed.
41 | */
42 | val input: TokenStream,
43 | /**
44 | * The token index in the input stream at which the current prediction was
45 | * originally invoked.
46 | */
47 | val startIndex: Int,
48 | /**
49 | * The token index in the input stream at which the current event occurred.
50 | */
51 | val stopIndex: Int,
52 | /**
53 | * `true` if the current event occurred during LL prediction;
54 | * otherwise, `false` if the input occurred during SLL prediction.
55 | */
56 | val fullCtx: Boolean)
57 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/DecisionState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | abstract class DecisionState : ATNState() {
10 | var decision = -1
11 | var nonGreedy: Boolean = false
12 | }
13 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/EmptyPredictionContext.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class EmptyPredictionContext : SingletonPredictionContext(null, PredictionContext.EMPTY_RETURN_STATE) {
10 |
11 | override val isEmpty: Boolean
12 | get() = true
13 |
14 | override fun size(): Int {
15 | return 1
16 | }
17 |
18 | override fun getParent(index: Int): PredictionContext? {
19 | return null
20 | }
21 |
22 | override fun getReturnState(index: Int): Int {
23 | // It was: return returnState
24 | // Changed because of https://youtrack.jetbrains.com/issue/KT-22161
25 | return PredictionContext.EMPTY_RETURN_STATE
26 | }
27 |
28 | override fun equals(o: Any?): Boolean {
29 | return this === o
30 | }
31 |
32 | override fun toString(): String {
33 | return "$"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/EpsilonTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class EpsilonTransition constructor(target: ATNState, private val outermostPrecedenceReturn: Int = -1) : Transition(target) {
10 |
11 | override val serializationType: Int
12 | get() = Transition.EPSILON
13 |
14 | override val isEpsilon: Boolean
15 | get() = true
16 |
17 | /**
18 | * @return the rule index of a precedence rule for which this transition is
19 | * returning from, where the precedence value is 0; otherwise, -1.
20 | *
21 | * @see ATNConfig.isPrecedenceFilterSuppressed
22 | * @see ParserATNSimulator.applyPrecedenceFilter
23 | * @since 4.4.1
24 | */
25 | fun outermostPrecedenceReturn(): Int {
26 | return outermostPrecedenceReturn
27 | }
28 |
29 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
30 | return false
31 | }
32 |
33 | override fun toString(): String {
34 | return "epsilon"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/ErrorInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.*
10 |
11 | /**
12 | * This class represents profiling event information for a syntax error
13 | * identified during prediction. Syntax errors occur when the prediction
14 | * algorithm is unable to identify an alternative which would lead to a
15 | * successful parse.
16 | *
17 | * @see Parser.notifyErrorListeners
18 | * @see ANTLRErrorListener.syntaxError
19 | *
20 | *
21 | * @since 4.3
22 | */
23 | class ErrorInfo
24 | /**
25 | * Constructs a new instance of the [ErrorInfo] class with the
26 | * specified detailed syntax error information.
27 | *
28 | * @param decision The decision number
29 | * @param configs The final configuration set reached during prediction
30 | * prior to reaching the [ATNSimulator.ERROR] state
31 | * @param input The input token stream
32 | * @param startIndex The start index for the current prediction
33 | * @param stopIndex The index at which the syntax error was identified
34 | * @param fullCtx `true` if the syntax error was identified during LL
35 | * prediction; otherwise, `false` if the syntax error was identified
36 | * during SLL prediction
37 | */
38 | (decision: Int,
39 | configs: ATNConfigSet,
40 | input: TokenStream, startIndex: Int, stopIndex: Int,
41 | fullCtx: Boolean) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx)
42 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.CharStream
10 | import org.antlr.v4.kotlinruntime.Lexer
11 |
12 | /**
13 | * Represents a single action which can be executed following the successful
14 | * match of a lexer rule. Lexer actions are used for both embedded action syntax
15 | * and ANTLR 4's new lexer command syntax.
16 | *
17 | * @author Sam Harwell
18 | * @since 4.2
19 | */
20 | interface LexerAction {
21 | /**
22 | * Gets the serialization type of the lexer action.
23 | *
24 | * @return The serialization type of the lexer action.
25 | */
26 | val actionType: LexerActionType
27 |
28 | /**
29 | * Gets whether the lexer action is position-dependent. Position-dependent
30 | * actions may have different semantics depending on the [CharStream]
31 | * index at the time the action is executed.
32 | *
33 | *
34 | * Many lexer commands, including `type`, `skip`, and
35 | * `more`, do not check the input index during their execution.
36 | * Actions like this are position-independent, and may be stored more
37 | * efficiently as part of the [LexerATNConfig.lexerActionExecutor].
38 | *
39 | * @return `true` if the lexer action semantics can be affected by the
40 | * position of the input [CharStream] at the time it is executed;
41 | * otherwise, `false`.
42 | */
43 | val isPositionDependent: Boolean
44 |
45 | /**
46 | * Execute the lexer action in the context of the specified [Lexer].
47 | *
48 | *
49 | * For position-dependent actions, the input stream must already be
50 | * positioned correctly prior to calling this method.
51 | *
52 | * @param lexer The lexer instance.
53 | */
54 | fun execute(lexer: Lexer)
55 | }
56 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerActionType.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | * Represents the serialization type of a [LexerAction].
11 | *
12 | * @author Sam Harwell
13 | * @since 4.2
14 | */
15 | enum class LexerActionType {
16 | /**
17 | * The type of a [LexerChannelAction] action.
18 | */
19 | CHANNEL,
20 | /**
21 | * The type of a [LexerCustomAction] action.
22 | */
23 | CUSTOM,
24 | /**
25 | * The type of a [LexerModeAction] action.
26 | */
27 | MODE,
28 | /**
29 | * The type of a [LexerMoreAction] action.
30 | */
31 | MORE,
32 | /**
33 | * The type of a [LexerPopModeAction] action.
34 | */
35 | POP_MODE,
36 | /**
37 | * The type of a [LexerPushModeAction] action.
38 | */
39 | PUSH_MODE,
40 | /**
41 | * The type of a [LexerSkipAction] action.
42 | */
43 | SKIP,
44 | /**
45 | * The type of a [LexerTypeAction] action.
46 | */
47 | TYPE
48 | }
49 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerChannelAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 | import org.antlr.v4.kotlinruntime.Token
12 |
13 | /**
14 | * Implements the `channel` lexer action by calling
15 | * [Lexer.setChannel] with the assigned channel.
16 | *
17 | * @author Sam Harwell
18 | * @since 4.2
19 | */
20 | class LexerChannelAction
21 | /**
22 | * Constructs a new `channel` action with the specified channel value.
23 | * @param channel The channel value to pass to [Lexer.setChannel].
24 | */
25 | (
26 | /**
27 | * Gets the channel to use for the [Token] created by the lexer.
28 | *
29 | * @return The channel to use for the [Token] created by the lexer.
30 | */
31 | val channel: Int) : LexerAction {
32 |
33 | /**
34 | * {@inheritDoc}
35 | * @return This method returns [LexerActionType.CHANNEL].
36 | */
37 | override val actionType: LexerActionType
38 | get() = LexerActionType.CHANNEL
39 |
40 | /**
41 | * {@inheritDoc}
42 | * @return This method returns `false`.
43 | */
44 | override val isPositionDependent: Boolean
45 | get() = false
46 |
47 | /**
48 | * {@inheritDoc}
49 | *
50 | *
51 | * This action is implemented by calling [Lexer.setChannel] with the
52 | * value provided by [.getChannel].
53 | */
54 | override fun execute(lexer: Lexer) {
55 | lexer.channel = channel
56 | }
57 |
58 | override fun hashCode(): Int {
59 | var hash = MurmurHash.initialize()
60 | hash = MurmurHash.update(hash, actionType.ordinal)
61 | hash = MurmurHash.update(hash, channel)
62 | return MurmurHash.finish(hash, 2)
63 | }
64 |
65 | override fun equals(obj: Any?): Boolean {
66 | if (obj === this) {
67 | return true
68 | } else if (obj !is LexerChannelAction) {
69 | return false
70 | }
71 |
72 | return channel == obj.channel
73 | }
74 |
75 | override fun toString(): String {
76 | return "channel($channel)"
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerModeAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `mode` lexer action by calling [Lexer.mode] with
14 | * the assigned mode.
15 | *
16 | * @author Sam Harwell
17 | * @since 4.2
18 | */
19 | class LexerModeAction
20 | /**
21 | * Constructs a new `mode` action with the specified mode value.
22 | * @param mode The mode value to pass to [Lexer.mode].
23 | */
24 | (
25 | /**
26 | * Get the lexer mode this action should transition the lexer to.
27 | *
28 | * @return The lexer mode for this `mode` command.
29 | */
30 | val mode: Int) : LexerAction {
31 |
32 | /**
33 | * {@inheritDoc}
34 | * @return This method returns [LexerActionType.MODE].
35 | */
36 | override val actionType: LexerActionType
37 | get() = LexerActionType.MODE
38 |
39 | /**
40 | * {@inheritDoc}
41 | * @return This method returns `false`.
42 | */
43 | override val isPositionDependent: Boolean
44 | get() = false
45 |
46 | /**
47 | * {@inheritDoc}
48 | *
49 | *
50 | * This action is implemented by calling [Lexer.mode] with the
51 | * value provided by [.getMode].
52 | */
53 | override fun execute(lexer: Lexer) {
54 | lexer.mode(mode)
55 | }
56 |
57 | override fun hashCode(): Int {
58 | var hash = MurmurHash.initialize()
59 | hash = MurmurHash.update(hash, actionType.ordinal)
60 | hash = MurmurHash.update(hash, mode)
61 | return MurmurHash.finish(hash, 2)
62 | }
63 |
64 | override fun equals(obj: Any?): Boolean {
65 | if (obj === this) {
66 | return true
67 | } else if (obj !is LexerModeAction) {
68 | return false
69 | }
70 |
71 | return mode == obj.mode
72 | }
73 |
74 | override fun toString(): String {
75 | return "mode($mode)"
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerMoreAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `more` lexer action by calling [Lexer.more].
14 | *
15 | *
16 | * The `more` command does not have any parameters, so this action is
17 | * implemented as a singleton instance exposed by [.INSTANCE].
18 | *
19 | * @author Sam Harwell
20 | * @since 4.2
21 | */
22 | class LexerMoreAction
23 | /**
24 | * Constructs the singleton instance of the lexer `more` command.
25 | */
26 | private constructor() : LexerAction {
27 |
28 | /**
29 | * {@inheritDoc}
30 | * @return This method returns [LexerActionType.MORE].
31 | */
32 | override val actionType: LexerActionType
33 | get() = LexerActionType.MORE
34 |
35 | /**
36 | * {@inheritDoc}
37 | * @return This method returns `false`.
38 | */
39 | override val isPositionDependent: Boolean
40 | get() = false
41 |
42 | /**
43 | * {@inheritDoc}
44 | *
45 | *
46 | * This action is implemented by calling [Lexer.more].
47 | */
48 | override fun execute(lexer: Lexer) {
49 | lexer.more()
50 | }
51 |
52 | override fun hashCode(): Int {
53 | var hash = MurmurHash.initialize()
54 | hash = MurmurHash.update(hash, actionType.ordinal)
55 | return MurmurHash.finish(hash, 1)
56 | }
57 |
58 | override fun equals(obj: Any?): Boolean {
59 | return obj === this
60 | }
61 |
62 | override fun toString(): String {
63 | return "more"
64 | }
65 |
66 | companion object {
67 | /**
68 | * Provides a singleton instance of this parameterless lexer action.
69 | */
70 | val INSTANCE = LexerMoreAction()
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPopModeAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `popMode` lexer action by calling [Lexer.popMode].
14 | *
15 | *
16 | * The `popMode` command does not have any parameters, so this action is
17 | * implemented as a singleton instance exposed by [.INSTANCE].
18 | *
19 | * @author Sam Harwell
20 | * @since 4.2
21 | */
22 | class LexerPopModeAction
23 | /**
24 | * Constructs the singleton instance of the lexer `popMode` command.
25 | */
26 | private constructor() : LexerAction {
27 |
28 | /**
29 | * {@inheritDoc}
30 | * @return This method returns [LexerActionType.POP_MODE].
31 | */
32 | override val actionType: LexerActionType
33 | get() = LexerActionType.POP_MODE
34 |
35 | /**
36 | * {@inheritDoc}
37 | * @return This method returns `false`.
38 | */
39 | override val isPositionDependent: Boolean
40 | get() = false
41 |
42 | /**
43 | * {@inheritDoc}
44 | *
45 | *
46 | * This action is implemented by calling [Lexer.popMode].
47 | */
48 | override fun execute(lexer: Lexer) {
49 | lexer.popMode()
50 | }
51 |
52 | override fun hashCode(): Int {
53 | var hash = MurmurHash.initialize()
54 | hash = MurmurHash.update(hash, actionType.ordinal)
55 | return MurmurHash.finish(hash, 1)
56 | }
57 |
58 | override fun equals(obj: Any?): Boolean {
59 | return obj === this
60 | }
61 |
62 | override fun toString(): String {
63 | return "popMode"
64 | }
65 |
66 | companion object {
67 | /**
68 | * Provides a singleton instance of this parameterless lexer action.
69 | */
70 | val INSTANCE = LexerPopModeAction()
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerPushModeAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `pushMode` lexer action by calling
14 | * [Lexer.pushMode] with the assigned mode.
15 | *
16 | * @author Sam Harwell
17 | * @since 4.2
18 | */
19 | class LexerPushModeAction
20 | /**
21 | * Constructs a new `pushMode` action with the specified mode value.
22 | * @param mode The mode value to pass to [Lexer.pushMode].
23 | */
24 | (
25 | /**
26 | * Get the lexer mode this action should transition the lexer to.
27 | *
28 | * @return The lexer mode for this `pushMode` command.
29 | */
30 | val mode: Int) : LexerAction {
31 |
32 | /**
33 | * {@inheritDoc}
34 | * @return This method returns [LexerActionType.PUSH_MODE].
35 | */
36 | override val actionType: LexerActionType
37 | get() = LexerActionType.PUSH_MODE
38 |
39 | /**
40 | * {@inheritDoc}
41 | * @return This method returns `false`.
42 | */
43 | override val isPositionDependent: Boolean
44 | get() = false
45 |
46 | /**
47 | * {@inheritDoc}
48 | *
49 | *
50 | * This action is implemented by calling [Lexer.pushMode] with the
51 | * value provided by [.getMode].
52 | */
53 | override fun execute(lexer: Lexer) {
54 | lexer.pushMode(mode)
55 | }
56 |
57 | override fun hashCode(): Int {
58 | var hash = MurmurHash.initialize()
59 | hash = MurmurHash.update(hash, actionType.ordinal)
60 | hash = MurmurHash.update(hash, mode)
61 | return MurmurHash.finish(hash, 2)
62 | }
63 |
64 | override fun equals(obj: Any?): Boolean {
65 | if (obj === this) {
66 | return true
67 | } else if (obj !is LexerPushModeAction) {
68 | return false
69 | }
70 |
71 | return mode == obj.mode
72 | }
73 |
74 | override fun toString(): String {
75 | return "pushMode($mode)"
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerSkipAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `skip` lexer action by calling [Lexer.skip].
14 | *
15 | *
16 | * The `skip` command does not have any parameters, so this action is
17 | * implemented as a singleton instance exposed by [.INSTANCE].
18 | *
19 | * @author Sam Harwell
20 | * @since 4.2
21 | */
22 | class LexerSkipAction
23 | /**
24 | * Constructs the singleton instance of the lexer `skip` command.
25 | */
26 | private constructor() : LexerAction {
27 |
28 | /**
29 | * {@inheritDoc}
30 | * @return This method returns [LexerActionType.SKIP].
31 | */
32 | override val actionType: LexerActionType
33 | get() = LexerActionType.SKIP
34 |
35 | /**
36 | * {@inheritDoc}
37 | * @return This method returns `false`.
38 | */
39 | override val isPositionDependent: Boolean
40 | get() = false
41 |
42 | /**
43 | * {@inheritDoc}
44 | *
45 | *
46 | * This action is implemented by calling [Lexer.skip].
47 | */
48 | override fun execute(lexer: Lexer) {
49 | lexer.skip()
50 | }
51 |
52 | override fun hashCode(): Int {
53 | var hash = MurmurHash.initialize()
54 | hash = MurmurHash.update(hash, actionType.ordinal)
55 | return MurmurHash.finish(hash, 1)
56 | }
57 |
58 | override fun equals(obj: Any?): Boolean {
59 | return obj === this
60 | }
61 |
62 | override fun toString(): String {
63 | return "skip"
64 | }
65 |
66 | companion object {
67 | /**
68 | * Provides a singleton instance of this parameterless lexer action.
69 | */
70 | val INSTANCE = LexerSkipAction()
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LexerTypeAction.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Lexer
10 | import org.antlr.v4.kotlinruntime.misc.MurmurHash
11 |
12 | /**
13 | * Implements the `type` lexer action by calling [Lexer.setType]
14 | * with the assigned type.
15 | *
16 | * @author Sam Harwell
17 | * @since 4.2
18 | */
19 | class LexerTypeAction
20 | /**
21 | * Constructs a new `type` action with the specified token type value.
22 | * @param type The type to assign to the token using [Lexer.setType].
23 | */
24 | (
25 | /**
26 | * Gets the type to assign to a token created by the lexer.
27 | * @return The type to assign to a token created by the lexer.
28 | */
29 | val type: Int) : LexerAction {
30 |
31 | /**
32 | * {@inheritDoc}
33 | * @return This method returns [LexerActionType.TYPE].
34 | */
35 | override val actionType: LexerActionType
36 | get() = LexerActionType.TYPE
37 |
38 | /**
39 | * {@inheritDoc}
40 | * @return This method returns `false`.
41 | */
42 | override val isPositionDependent: Boolean
43 | get() = false
44 |
45 | /**
46 | * {@inheritDoc}
47 | *
48 | *
49 | * This action is implemented by calling [Lexer.setType] with the
50 | * value provided by [.getType].
51 | */
52 | override fun execute(lexer: Lexer) {
53 | lexer.type = type
54 | }
55 |
56 | override fun hashCode(): Int {
57 | var hash = MurmurHash.initialize()
58 | hash = MurmurHash.update(hash, actionType.ordinal)
59 | hash = MurmurHash.update(hash, type)
60 | return MurmurHash.finish(hash, 2)
61 | }
62 |
63 | override fun equals(obj: Any?): Boolean {
64 | if (obj === this) {
65 | return true
66 | } else if (obj !is LexerTypeAction) {
67 | return false
68 | }
69 |
70 | return type == obj.type
71 | }
72 |
73 | override fun toString(): String {
74 | return "type($type)"
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LookaheadEventInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.TokenStream
10 |
11 | /**
12 | * This class represents profiling event information for tracking the lookahead
13 | * depth required in order to make a prediction.
14 | *
15 | * @since 4.3
16 | */
17 | class LookaheadEventInfo
18 | /**
19 | * Constructs a new instance of the [LookaheadEventInfo] class with
20 | * the specified detailed lookahead information.
21 | *
22 | * @param decision The decision number
23 | * @param configs The final configuration set containing the necessary
24 | * information to determine the result of a prediction, or `null` if
25 | * the final configuration set is not available
26 | * @param input The input token stream
27 | * @param startIndex The start index for the current prediction
28 | * @param stopIndex The index at which the prediction was finally made
29 | * @param fullCtx `true` if the current lookahead is part of an LL
30 | * prediction; otherwise, `false` if the current lookahead is part of
31 | * an SLL prediction
32 | */
33 | (decision: Int,
34 | configs: ATNConfigSet,
35 | /** The alternative chosen by adaptivePredict(), not necessarily
36 | * the outermost alt shown for a rule; left-recursive rules have
37 | * user-level alts that differ from the rewritten rule with a (...) block
38 | * and a (..)* loop.
39 | */
40 | var predictedAlt: Int,
41 | input: TokenStream, startIndex: Int, stopIndex: Int,
42 | fullCtx: Boolean) : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx)
43 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/LoopEndState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** Mark the end of a * or + loop. */
10 | class LoopEndState : ATNState() {
11 | var loopBackState: ATNState? = null
12 |
13 | override val stateType: Int
14 | get() = ATNState.LOOP_END
15 | }
16 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/NotSetTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet
10 |
11 | class NotSetTransition(target: ATNState, set: IntervalSet) : SetTransition(target, set) {
12 |
13 | override val serializationType: Int
14 | get() = Transition.NOT_SET
15 |
16 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
17 | return (symbol >= minVocabSymbol
18 | && symbol <= maxVocabSymbol
19 | && !super.matches(symbol, minVocabSymbol, maxVocabSymbol))
20 | }
21 |
22 | override fun toString(): String {
23 | return '~' + super.toString()
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/OrderedATNConfigSet.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.misc.ObjectEqualityComparator
10 |
11 | /**
12 | *
13 | * @author Sam Harwell
14 | */
15 | class OrderedATNConfigSet : ATNConfigSet() {
16 | init {
17 | this.configLookup = LexerConfigHashSet()
18 | }
19 |
20 | class LexerConfigHashSet : ATNConfigSet.AbstractConfigHashSet(ObjectEqualityComparator.INSTANCE) {
21 | override fun remove(element: ATNConfig): Boolean {
22 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
23 | }
24 |
25 | override fun containsAll(elements: Collection): Boolean {
26 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
27 | }
28 |
29 | override fun retainAll(elements: Collection): Boolean {
30 | TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PlusBlockStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** Start of `(A|B|...)+` loop. Technically a decision state, but
10 | * we don't use for code generation; somebody might need it, so I'm defining
11 | * it for completeness. In reality, the [PlusLoopbackState] node is the
12 | * real decision-making note for `A+`.
13 | */
14 | class PlusBlockStartState : BlockStartState() {
15 | var loopBackState: PlusLoopbackState? = null
16 |
17 | override val stateType: Int
18 | get() = ATNState.PLUS_BLOCK_START
19 | }
20 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PlusLoopbackState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** Decision state for `A+` and `(A|B)+`. It has two transitions:
10 | * one to the loop back to start of the block and one to exit.
11 | */
12 | class PlusLoopbackState : DecisionState() {
13 |
14 | override val stateType: Int
15 | get() = ATNState.PLUS_LOOP_BACK
16 | }
17 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PrecedencePredicateTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /**
10 | *
11 | * @author Sam Harwell
12 | */
13 | class PrecedencePredicateTransition(target: ATNState, val precedence: Int) : AbstractPredicateTransition(target) {
14 |
15 | override val serializationType: Int
16 | get() = Transition.PRECEDENCE
17 |
18 | override val isEpsilon: Boolean
19 | get() = true
20 |
21 | val predicate: SemanticContext.PrecedencePredicate
22 | get() = SemanticContext.PrecedencePredicate(precedence)
23 |
24 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
25 | return false
26 | }
27 |
28 | override fun toString(): String {
29 | return precedence.toString() + " >= _p"
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredicateEvalInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.ParserRuleContext
10 | import org.antlr.v4.kotlinruntime.Recognizer
11 | import org.antlr.v4.kotlinruntime.RuleContext
12 | import org.antlr.v4.kotlinruntime.TokenStream
13 |
14 | /**
15 | * This class represents profiling event information for semantic predicate
16 | * evaluations which occur during prediction.
17 | *
18 | * @see ParserATNSimulator.evalSemanticContext
19 | *
20 | *
21 | * @since 4.3
22 | */
23 | class PredicateEvalInfo
24 | /**
25 | * Constructs a new instance of the [PredicateEvalInfo] class with the
26 | * specified detailed predicate evaluation information.
27 | *
28 | * @param decision The decision number
29 | * @param input The input token stream
30 | * @param startIndex The start index for the current prediction
31 | * @param stopIndex The index at which the predicate evaluation was
32 | * triggered. Note that the input stream may be reset to other positions for
33 | * the actual evaluation of individual predicates.
34 | * @param semctx The semantic context which was evaluated
35 | * @param evalResult The results of evaluating the semantic context
36 | * @param predictedAlt The alternative number for the decision which is
37 | * guarded by the semantic context `semctx`. See [.predictedAlt]
38 | * for more information.
39 | * @param fullCtx `true` if the semantic context was
40 | * evaluated during LL prediction; otherwise, `false` if the semantic
41 | * context was evaluated during SLL prediction
42 | *
43 | * @see ParserATNSimulator.evalSemanticContext
44 | * @see SemanticContext.eval
45 | */
46 | (decision: Int,
47 | input: TokenStream, startIndex: Int, stopIndex: Int,
48 | /**
49 | * The semantic context which was evaluated.
50 | */
51 | val semctx: SemanticContext,
52 | /**
53 | * The result of evaluating the semantic context [.semctx].
54 | */
55 | val evalResult: Boolean,
56 | /**
57 | * The alternative number for the decision which is guarded by the semantic
58 | * context [.semctx]. Note that other ATN
59 | * configurations may predict the same alternative which are guarded by
60 | * other semantic contexts and/or [SemanticContext.NONE].
61 | */
62 | val predictedAlt: Int,
63 | fullCtx: Boolean) : DecisionEventInfo(decision, ATNConfigSet(), input, startIndex, stopIndex, fullCtx)
64 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredicateTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** TODO: this is old comment:
10 | * A tree of semantic predicates from the grammar AST if accessLabel==SEMPRED.
11 | * In the ATN, labels will always be exactly one predicate, but the DFA
12 | * may have to combine a bunch of them as it collects predicates from
13 | * multiple ATN configurations into a single DFA state.
14 | */
15 | class PredicateTransition(target: ATNState, val ruleIndex: Int, val predIndex: Int, val isCtxDependent: Boolean // e.g., $i ref in pred
16 | ) : AbstractPredicateTransition(target) {
17 |
18 | override val serializationType: Int
19 | get() = Transition.PREDICATE
20 |
21 | override val isEpsilon: Boolean
22 | get() = true
23 |
24 | val predicate: SemanticContext.Predicate
25 | get() = SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent)
26 |
27 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
28 | return false
29 | }
30 |
31 | override fun toString(): String {
32 | return "pred_$ruleIndex:$predIndex"
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/PredictionContextCache.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** Used to cache [PredictionContext] objects. Its used for the shared
10 | * context cash associated with contexts in DFA states. This cache
11 | * can be used for both lexers and parsers.
12 | */
13 | class PredictionContextCache {
14 | protected val cache: MutableMap = HashMap()
15 |
16 | /** Add a context to the cache and return it. If the context already exists,
17 | * return that one instead and do not add a new context to the cache.
18 | * Protect shared cache from unsafe thread access.
19 | */
20 | fun add(ctx: PredictionContext): PredictionContext {
21 | if (ctx === PredictionContext.EMPTY) return PredictionContext.EMPTY
22 | val existing = cache[ctx]
23 | if (existing != null) {
24 | // System.out.println(name+" reuses "+existing);
25 | return existing
26 | }
27 | cache.put(ctx, ctx)
28 | return ctx
29 | }
30 |
31 | operator fun get(ctx: PredictionContext): PredictionContext? {
32 | return cache[ctx]
33 | }
34 |
35 | fun size(): Int {
36 | return cache.size
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RangeTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.misc.IntervalSet
10 |
11 | class RangeTransition(target: ATNState, val from: Int, val to: Int) : Transition(target) {
12 |
13 | override val serializationType: Int
14 | get() = Transition.RANGE
15 |
16 | override fun accessLabel(): IntervalSet? {
17 | return IntervalSet.of(from, to)
18 | }
19 |
20 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
21 | return symbol >= from && symbol <= to
22 | }
23 |
24 | override fun toString(): String {
25 | TODO()
26 | // return StringBuilder("'")
27 | // .appendCodePoint(from)
28 | // .append("'..'")
29 | // .appendCodePoint(to)
30 | // .append("'")
31 | // .toString()
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class RuleStartState : ATNState() {
10 | var stopState: RuleStopState? = null
11 | var isLeftRecursiveRule: Boolean = false
12 |
13 | override val stateType: Int
14 | get() = ATNState.RULE_START
15 | }
16 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleStopState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** The last node in the ATN for a rule, unless that rule is the start symbol.
10 | * In that case, there is one transition to EOF. Later, we might encode
11 | * references to all calls to this rule to compute FOLLOW sets for
12 | * error handling.
13 | */
14 | class RuleStopState : ATNState() {
15 |
16 | override val stateType: Int
17 | get() = ATNState.RULE_STOP
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/RuleTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** */
10 | class RuleTransition(ruleStart: RuleStartState,
11 | /** Ptr to the rule definition object for this rule ref */
12 | val ruleIndex: Int // no Rule object at runtime
13 | ,
14 | val precedence: Int,
15 | /** What node to begin computations following ref to rule */
16 | var followState: ATNState) : Transition(ruleStart) {
17 |
18 | override val serializationType: Int
19 | get() = Transition.RULE
20 |
21 | override val isEpsilon: Boolean
22 | get() = true
23 |
24 |
25 | @Deprecated("Use\n" +
26 | "\t {@link #RuleTransition(RuleStartState, int, int, ATNState)} instead.")
27 | constructor(ruleStart: RuleStartState,
28 | ruleIndex: Int,
29 | followState: ATNState) : this(ruleStart, ruleIndex, 0, followState) {
30 | }
31 |
32 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
33 | return false
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/SetTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.Token
10 | import org.antlr.v4.kotlinruntime.misc.IntervalSet
11 |
12 | /** A transition containing a set of values. */
13 | open class SetTransition// TODO (sam): should we really allow null here?
14 | (target: ATNState, set: IntervalSet?) : Transition(target) {
15 | val set: IntervalSet
16 |
17 | override val serializationType: Int
18 | get() = Transition.SET
19 |
20 | init {
21 | var set = set
22 | if (set == null) set = IntervalSet.of(Token.INVALID_TYPE)
23 | this.set = set
24 | }
25 |
26 | override fun accessLabel(): IntervalSet? {
27 | return set
28 | }
29 |
30 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
31 | return set.contains(symbol)
32 | }
33 |
34 | override fun toString(): String {
35 | return set.toString()
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/SingletonPredictionContext.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import com.strumenta.kotlinmultiplatform.assert
10 |
11 | open class SingletonPredictionContext internal constructor(val parent: PredictionContext?, val returnState: Int) : PredictionContext(if (parent != null) PredictionContext.calculateHashCode(parent, returnState) else PredictionContext.calculateEmptyHashCode()) {
12 |
13 | init {
14 | assert(returnState != ATNState.INVALID_STATE_NUMBER)
15 | }
16 |
17 | override fun size(): Int {
18 | return 1
19 | }
20 |
21 | override fun getParent(index: Int): PredictionContext? {
22 | assert(index == 0)
23 | return parent
24 | }
25 |
26 | override fun getReturnState(index: Int): Int {
27 | assert(index == 0)
28 | return returnState
29 | }
30 |
31 | override fun equals(o: Any?): Boolean {
32 | if (this === o) {
33 | return true
34 | } else if (o !is SingletonPredictionContext) {
35 | return false
36 | }
37 |
38 | if (this.hashCode() != o.hashCode()) {
39 | return false // can't be same if hash is different
40 | }
41 |
42 | val s = o as SingletonPredictionContext?
43 | return returnState == s!!.returnState && parent != null && parent == s.parent
44 | }
45 |
46 | override fun toString(): String {
47 | val up = if (parent != null) parent!!.toString() else ""
48 | return if (up.length == 0) {
49 | if (returnState == PredictionContext.EMPTY_RETURN_STATE) {
50 | "$"
51 | } else returnState.toString()
52 | } else returnState.toString() + " " + up
53 | }
54 |
55 | companion object {
56 |
57 | fun create(parent: PredictionContext?, returnState: Int): SingletonPredictionContext {
58 | return if (returnState == PredictionContext.EMPTY_RETURN_STATE && parent == null) {
59 | // someone can pass in the bits of an array ctx that mean $
60 | PredictionContext.EMPTY
61 | } else SingletonPredictionContext(parent, returnState)
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarBlockStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** The block that begins a closure loop. */
10 | class StarBlockStartState : BlockStartState() {
11 |
12 | override val stateType: Int
13 | get() = ATNState.STAR_BLOCK_START
14 | }
15 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopEntryState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | import org.antlr.v4.kotlinruntime.dfa.DFA
10 |
11 | class StarLoopEntryState : DecisionState() {
12 | var loopBackState: StarLoopbackState? = null
13 |
14 | /**
15 | * Indicates whether this state can benefit from a precedence DFA during SLL
16 | * decision making.
17 | *
18 | *
19 | * This is a computed property that is calculated during ATN deserialization
20 | * and stored for use in [ParserATNSimulator] and
21 | * [ParserInterpreter].
22 | *
23 | * @see DFA.isPrecedenceDfa
24 | */
25 | var isPrecedenceDecision: Boolean = false
26 |
27 | override val stateType: Int
28 | get() = ATNState.STAR_LOOP_ENTRY
29 | }
30 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/StarLoopbackState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class StarLoopbackState : ATNState() {
10 | val loopEntryState: StarLoopEntryState
11 | get() = transition(0).target as StarLoopEntryState
12 |
13 | override val stateType: Int
14 | get() = ATNState.STAR_LOOP_BACK
15 | }
16 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/TokensStartState.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | /** The Tokens rule start state linking to each lexer rule start state */
10 | class TokensStartState : DecisionState() {
11 |
12 | override val stateType: Int
13 | get() = ATNState.TOKEN_START
14 | }
15 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/atn/WildcardTransition.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.atn
8 |
9 | class WildcardTransition(target: ATNState) : Transition(target) {
10 |
11 | override val serializationType: Int
12 | get() = Transition.WILDCARD
13 |
14 | override fun matches(symbol: Int, minVocabSymbol: Int, maxVocabSymbol: Int): Boolean {
15 | return symbol >= minVocabSymbol && symbol <= maxVocabSymbol
16 | }
17 |
18 | override fun toString(): String {
19 | return "."
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/dfa/DFASerializer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.dfa
8 |
9 | import com.strumenta.kotlinmultiplatform.Arrays
10 | import org.antlr.v4.kotlinruntime.Vocabulary
11 | import org.antlr.v4.kotlinruntime.VocabularyImpl
12 |
13 | /** A DFA walker that knows how to dump them to serialized strings. */
14 | open class DFASerializer {
15 |
16 | private val dfa: DFA
17 |
18 | private val vocabulary: Vocabulary
19 |
20 |
21 | @Deprecated("Use {@link #DFASerializer(DFA, Vocabulary)} instead.")
22 | constructor(dfa: DFA, tokenNames: Array) : this(dfa, VocabularyImpl.fromTokenNames(tokenNames as Array)) {
23 | }
24 |
25 | constructor(dfa: DFA, vocabulary: Vocabulary) {
26 | this.dfa = dfa
27 | this.vocabulary = vocabulary
28 | }
29 |
30 | override fun toString(): String {
31 | if (dfa.s0 == null) return "null"
32 | val buf = StringBuilder()
33 | val states = dfa.getStates()
34 | for (s in states) {
35 | var n = 0
36 | if (s.edges != null) n = s.edges!!.size
37 | for (i in 0 until n) {
38 | val t = s.edges!![i]
39 | if (t != null && t!!.stateNumber != Int.MAX_VALUE) {
40 | buf.append(getStateString(s))
41 | val label = getEdgeLabel(i)
42 | buf.append("-").append(label).append("->").append(getStateString(t)).append('\n')
43 | }
44 | }
45 | }
46 |
47 | val output = buf.toString()
48 | return if (output.length == 0) "null" else output
49 | //return Utils.sortLinesInString(output);
50 | }
51 |
52 | protected open fun getEdgeLabel(i: Int): String {
53 | return vocabulary.getDisplayName(i - 1)
54 | }
55 |
56 |
57 | protected fun getStateString(s: DFAState): String {
58 | val n = s.stateNumber
59 | val baseStateStr = (if (s.isAcceptState) ":" else "") + "s" + n + if (s.requiresFullContext) "^" else ""
60 | return if (s.isAcceptState) {
61 | if (s.predicates != null) {
62 | baseStateStr + "=>" + Arrays.toString(s.predicates!!)
63 | } else {
64 | baseStateStr + "=>" + s.prediction
65 | }
66 | } else {
67 | baseStateStr
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/dfa/LexerDFASerializer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.dfa
8 |
9 | import org.antlr.v4.kotlinruntime.VocabularyImpl
10 |
11 | class LexerDFASerializer(dfa: DFA) : DFASerializer(dfa, VocabularyImpl.EMPTY_VOCABULARY) {
12 |
13 | protected override fun getEdgeLabel(i: Int): String {
14 | TODO()
15 | // return StringBuilder("'")
16 | // .appendCodePoint(i)
17 | // .append("'")
18 | // .toString()
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/AbstractEqualityComparator.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime.misc
7 |
8 | /**
9 | * This abstract base class is provided so performance-critical applications can
10 | * use virtual- instead of interface-dispatch when calling comparator methods.
11 | *
12 | * @author Sam Harwell
13 | */
14 | abstract class AbstractEqualityComparator : EqualityComparator
15 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/DoubleKeyMap.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | /** Sometimes we need to map a key to a value but key is two pieces of data.
10 | * This nested hash table saves creating a single key each time we access
11 | * map; avoids mem creation.
12 | */
13 | class DoubleKeyMap {
14 | internal var data: MutableMap> = LinkedHashMap()
15 |
16 | fun put(k1: Key1, k2: Key2, v: Value): Value? {
17 | var data2: MutableMap? = data[k1]
18 | var prev: Value? = null
19 | if (data2 == null) {
20 | data2 = LinkedHashMap()
21 | data.put(k1, data2)
22 | } else {
23 | prev = data2[k2]
24 | }
25 | data2.put(k2, v)
26 | return prev
27 | }
28 |
29 | operator fun get(k1: Key1, k2: Key2): Value? {
30 | val data2 = data[k1] ?: return null
31 | return data2[k2]
32 | }
33 |
34 | operator fun get(k1: Key1): Map {
35 | return data[k1]!!
36 | }
37 |
38 | /** Get all values associated with primary key */
39 | fun values(k1: Key1): Collection? {
40 | val data2 = data[k1] ?: return null
41 | return data2.values
42 | }
43 |
44 | /** get all primary keys */
45 | fun keySet(): Set {
46 | return data.keys
47 | }
48 |
49 | /** get all secondary keys associated with a primary key */
50 | fun keySet(k1: Key1): Set? {
51 | val data2 = data[k1] ?: return null
52 | return data2.keys
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/EqualityComparator.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime.misc
7 |
8 | /**
9 | * This interface provides an abstract concept of object equality independent of
10 | * [Object.equals] (object equality) and the `==` operator
11 | * (reference equality). It can be used to provide algorithm-specific unordered
12 | * comparisons without requiring changes to the object itself.
13 | *
14 | * @author Sam Harwell
15 | */
16 | interface EqualityComparator {
17 |
18 | /**
19 | * This method returns a hash code for the specified object.
20 | *
21 | * @param obj The object.
22 | * @return The hash code for `obj`.
23 | */
24 | fun hashCode(obj: T): Int
25 |
26 | /**
27 | * This method tests if two objects are equal.
28 | *
29 | * @param a The first object to compare.
30 | * @param b The second object to compare.
31 | * @return `true` if `a` equals `b`, otherwise `false`.
32 | */
33 | fun equals(a: T?, b: T?): Boolean
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/IntegerStack.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime.misc
7 |
8 | /**
9 | *
10 | * @author Sam Harwell
11 | */
12 | class IntegerStack : IntegerList {
13 |
14 | constructor() {}
15 |
16 | constructor(capacity: Int) : super(capacity) {}
17 |
18 | constructor(list: IntegerStack) : super(list) {}
19 |
20 | fun push(value: Int) {
21 | add(value)
22 | }
23 |
24 | fun pop(): Int {
25 | return removeAt(size() - 1)
26 | }
27 |
28 | fun peek(): Int {
29 | return get(size() - 1)
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/MultiMap.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | class MultiMap : MutableMap> by mutableMapOf() {
10 |
11 | val pairs: List>
12 | get() {
13 | val pairs = ArrayList>()
14 | for (key in keys) {
15 | for (value in get(key)!!) {
16 | pairs.add(Pair(key, value))
17 | }
18 | }
19 | return pairs
20 | }
21 |
22 | fun map(key: K, value: V) {
23 | var elementsForKey: MutableList? = get(key)
24 | if (elementsForKey == null) {
25 | elementsForKey = ArrayList()
26 | put(key, elementsForKey)
27 | }
28 | elementsForKey.add(value)
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/NotNull.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime.misc
7 |
8 | @Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.LOCAL_VARIABLE)
9 | @Deprecated("THIS IS HERE FOR BACKWARD COMPATIBILITY WITH 4.5 ONLY. It will\n" +
10 | " disappear in 4.6+")
11 | annotation class NotNull
12 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/ObjectEqualityComparator.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 | package org.antlr.v4.kotlinruntime.misc
7 |
8 | /**
9 | * This default implementation of [EqualityComparator] uses object equality
10 | * for comparisons by calling [Object.hashCode] and [Object.equals].
11 | *
12 | * @author Sam Harwell
13 | */
14 | class ObjectEqualityComparator : AbstractEqualityComparator() {
15 | override fun hashCode(obj: T): Int {
16 | return obj?.hashCode() ?: 0
17 | }
18 |
19 | /**
20 | * {@inheritDoc}
21 | *
22 | *
23 | * This implementation relies on object equality. If both objects are
24 | * `null`, this method returns `true`. Otherwise if only
25 | * `a` is `null`, this method returns `false`. Otherwise,
26 | * this method returns the result of
27 | * `a.`[equals][Object.equals]`(b)`.
28 | */
29 | override fun equals(a: T?, b: T?): Boolean {
30 | return if (a == null) {
31 | b == null
32 | } else a == b
33 | }
34 |
35 |
36 |
37 | companion object {
38 | val INSTANCE = ObjectEqualityComparator()
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/OrderedHashSet.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | /** A HashMap that remembers the order that the elements were added.
10 | * You can alter the ith element with set(i,value) too :) Unique list.
11 | * I need the replace/set-element-i functionality so I'm subclassing
12 | * LinkedHashSet.
13 | */
14 | class OrderedHashSet : Set by mutableSetOf() {
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Pair.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | class Pair(val a: A?, val b: B?) {
10 |
11 | override fun equals(obj: Any?): Boolean {
12 | if (obj === this) {
13 | return true
14 | } else if (obj !is Pair<*, *>) {
15 | return false
16 | }
17 |
18 | val other = obj as Pair<*, *>?
19 | return ObjectEqualityComparator().equals(a, other!!.a) && ObjectEqualityComparator().equals(b, other.b)
20 | }
21 |
22 | override fun hashCode(): Int {
23 | var hash = MurmurHash.initialize()
24 | hash = MurmurHash.update(hash, a)
25 | hash = MurmurHash.update(hash, b)
26 | return MurmurHash.finish(hash, 2)
27 | }
28 |
29 | override fun toString(): String {
30 | return "($a, $b)"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/ParseCancellationException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | import org.antlr.v4.kotlinruntime.BailErrorStrategy
10 | import org.antlr.v4.kotlinruntime.RecognitionException
11 |
12 | /**
13 | * This exception is thrown to cancel a parsing operation. This exception does
14 | * not extend [RecognitionException], allowing it to bypass the standard
15 | * error recovery mechanisms. [BailErrorStrategy] throws this exception in
16 | * response to a parse error.
17 | *
18 | * @author Sam Harwell
19 | */
20 | class ParseCancellationException : RuntimeException {
21 |
22 | constructor() {}
23 |
24 | constructor(message: String) {}
25 |
26 | constructor(cause: Throwable) {
27 | TODO()
28 | //initCause(cause)
29 | }
30 |
31 | constructor(message: String, cause: Throwable) {
32 | TODO()
33 | //initCause(cause)
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Predicate.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | interface Predicate {
10 | fun test(t: T): Boolean
11 | }
12 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/misc/Triple.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.misc
8 |
9 | class Triple(val a: A, val b: B, val c: C) {
10 |
11 | override fun equals(obj: Any?): Boolean {
12 | if (obj === this) {
13 | return true
14 | } else if (obj !is Triple<*, *, *>) {
15 | return false
16 | }
17 |
18 | val other = obj as Triple<*, *, *>?
19 | return (ObjectEqualityComparator().equals(a, other!!.a)
20 | && ObjectEqualityComparator().equals(b, other.b)
21 | && ObjectEqualityComparator().equals(c, other.c))
22 | }
23 |
24 | override fun hashCode(): Int {
25 | var hash = MurmurHash.initialize()
26 | hash = MurmurHash.update(hash, a)
27 | hash = MurmurHash.update(hash, b)
28 | hash = MurmurHash.update(hash, c)
29 | return MurmurHash.finish(hash, 3)
30 | }
31 |
32 | override fun toString(): String {
33 | return "($a, $b, $c)"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNode.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.tree
8 |
9 | interface ErrorNode : TerminalNode
10 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ErrorNodeImpl.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.tree
8 |
9 | import org.antlr.v4.kotlinruntime.Token
10 |
11 | /** Represents a token that was consumed during resynchronization
12 | * rather than during a valid match operation. For example,
13 | * we will create this kind of a node during single token insertion
14 | * and deletion as well as during "consume until error recovery set"
15 | * upon no viable alternative exceptions.
16 | */
17 | class ErrorNodeImpl(token: Token) : TerminalNodeImpl(token), ErrorNode {
18 |
19 | override fun accept(visitor: ParseTreeVisitor): T?{
20 | return visitor.visitErrorNode(this)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTree.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.tree
8 |
9 | import org.antlr.v4.kotlinruntime.Parser
10 | import org.antlr.v4.kotlinruntime.RuleContext
11 | import org.antlr.v4.kotlinruntime.Token
12 |
13 | /** An interface to access the tree of [RuleContext] objects created
14 | * during a parse that makes the data structure look like a simple parse tree.
15 | * This node represents both internal nodes, rule invocations,
16 | * and leaf nodes, token matches.
17 | *
18 | *
19 | * The payload is either a [Token] or a [RuleContext] object.
20 | */
21 | interface ParseTree : SyntaxTree {
22 | // the following methods narrow the return type; they are not additional methods
23 | //override var parent: ParseTree?
24 |
25 | //private var parent : ParseTree? = null
26 |
27 | fun assignParent(value: ParseTree?)
28 | // this.parent = value
29 | //}
30 |
31 | override fun readParent() : ParseTree?
32 |
33 | /** Return the combined text of all leaf nodes. Does not get any
34 | * off-channel tokens (if any) so won't return whitespace and
35 | * comments if they are sent to parser on hidden channel.
36 | */
37 | val text: String
38 |
39 | override fun getChild(i: Int): ParseTree?
40 |
41 |
42 | /** Set the parent for this node.
43 | *
44 | * This is not backward compatible as it changes
45 | * the interface but no one was able to create custom
46 | * nodes anyway so I'm adding as it improves internal
47 | * code quality.
48 | *
49 | * One could argue for a restructuring of
50 | * the class/interface hierarchy so that
51 | * setParent, addChild are moved up to Tree
52 | * but that's a major change. So I'll do the
53 | * minimal change, which is to add this method.
54 | *
55 | * @since 4.7
56 | */
57 | //fun setParent(parent: RuleContext)
58 |
59 | /** The [ParseTreeVisitor] needs a double dispatch method. */
60 | fun accept(visitor: ParseTreeVisitor): T?
61 |
62 | /** Specialize toStringTree so that it can print out more information
63 | * based upon the parser.
64 | */
65 | fun toStringTree(parser: Parser): String
66 | }
67 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeListener.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.tree
8 |
9 | import org.antlr.v4.kotlinruntime.ParserRuleContext
10 |
11 | /** This interface describes the minimal core of methods triggered
12 | * by [ParseTreeWalker]. E.g.,
13 | *
14 | * ParseTreeWalker walker = new ParseTreeWalker();
15 | * walker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener
16 | *
17 | * If you want to trigger events in multiple listeners during a single
18 | * tree walk, you can use the ParseTreeDispatcher object available at
19 | *
20 | * https://github.com/antlr/antlr4/issues/841
21 | */
22 | interface ParseTreeListener {
23 | fun visitTerminal(node: TerminalNode)
24 | fun visitErrorNode(node: ErrorNode)
25 | fun enterEveryRule(ctx: ParserRuleContext)
26 | fun exitEveryRule(ctx: ParserRuleContext)
27 | }
28 |
--------------------------------------------------------------------------------
/antlr-kotlin-runtime-common/src/main/kotlin/org/antlr/v4/kotlinruntime/tree/ParseTreeProperty.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
3 | * Use of this file is governed by the BSD 3-clause license that
4 | * can be found in the LICENSE.txt file in the project root.
5 | */
6 |
7 | package org.antlr.v4.kotlinruntime.tree
8 |
9 | import com.strumenta.kotlinmultiplatform.IdentityHashMap
10 |
11 | /**
12 | * Associate a property with a parse tree node. Useful with parse tree listeners
13 | * that need to associate values with particular tree nodes, kind of like
14 | * specifying a return value for the listener event method that visited a
15 | * particular node. Example:
16 | *
17 | *