From ee6f4ccb4371f757927917740bfa40ecb1eecdd6 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Tue, 22 Mar 2022 16:14:00 +0300 Subject: [PATCH 01/29] VERSIONING: version changes --- build.gradle.kts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 1c7129e9..cf2a0d77 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -22,11 +22,8 @@ val mvnPassword: String? by project val mvnPublicationVersion: String? by project val candidates: String? by project -println("Provided Maven username of length ${mvnUsername?.length}") -println("Provided Maven password of length ${mvnPassword?.length}") - group = "org.polystat" -version = mvnPublicationVersion ?: "0.2.0" +version = mvnPublicationVersion ?: "0.3.0" val compileKotlin: KotlinCompile by tasks compileKotlin.kotlinOptions { From 361863e6c0f36b009b5de9f093f1c1023e5cd3e3 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Tue, 26 Apr 2022 20:44:27 +0300 Subject: [PATCH 02/29] FEATURE: logging modified Note For better UX --- .gitignore | 2 +- src/main/java/main/Main2.kt | 34 +++++++++++++++++++++++----------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 794fe3a3..0dc48725 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ out .idea build compile_and_run_tests.bat -j2eo.jar +*.jar output.eo output_eo polystat_check diff --git a/src/main/java/main/Main2.kt b/src/main/java/main/Main2.kt index 003b16e2..c0a800d3 100644 --- a/src/main/java/main/Main2.kt +++ b/src/main/java/main/Main2.kt @@ -10,6 +10,7 @@ import parser.Visitor import translator.Translator import tree.Compilation.CompilationUnit import tree.Entity +import util.logger import java.io.File import java.io.FileNotFoundException import java.nio.file.Files @@ -41,14 +42,14 @@ object Main2 { cmdLineParser.parse(options, args) } catch (e: ParseException) { e.printStackTrace() - System.err.println("Failed parsing command-line arguments") + logger.error("Failed parsing command-line arguments") printUsage(formatter, options) exitProcess(1) } // Check argv for all required data if (cmd.argList.size != 1) { - System.err.println("1 argument should be passed, but ${cmd.argList.size} were passed") + logger.error("1 argument should be passed, but ${cmd.argList.size} were passed") printUsage(formatter, options) exitProcess(1) } @@ -62,7 +63,7 @@ object Main2 { throw FileNotFoundException("No source file or directory found at \"$inputFilepath\"") } - println("Parsing files in directory \"${sourceFile.absolutePath}\"") + logger.info("Parsing files in directory \"${sourceFile.absolutePath}\"") val filesToProcess: List = if (sourceFile.isDirectory) sourceFile.walk() @@ -72,13 +73,15 @@ object Main2 { else listOf(sourceFile) - println("List of files to translate:" + filesToProcess.joinToString("") { "\n ${it.path}" }) + if (cmd.hasOption("d")) { + logger.debug("List of files to translate:" + filesToProcess.joinToString("") { "\n ${it.path}" }) + } val translatedFiles: List> = filesToProcess .reversed() - .mapIndexedNotNull { i, f -> + .mapIndexed { i, f -> //println("[${i+1}/${filesToProcess.size}] Parsing ${f.absolutePath}") - Scanner(f).use { scanner -> + Scanner(f).use { _ -> val lexer = JavaLexer(CharStreams.fromFileName(f.absolutePath)) val parser = JavaParser(CommonTokenStream(lexer)) val tree = parser.compilationUnit() @@ -86,15 +89,21 @@ object Main2 { val eval = Visitor() val cu = eval.visit(tree) as CompilationUnit - if (Entity.debug) + if (Entity.debug) { cu.report(0) + logger.debug("[${i+1}/${filesToProcess.size}] Translating ${f.absolutePath}") + } else { + if (i % 100 == 0) { + val percent = (1f * i / filesToProcess.size) * 100f + print("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}\r") + } + } - println("[${i+1}/${filesToProcess.size}] Translating ${f.absolutePath}") val translator = Translator() Pair(f, translator.translate(cu)) } } - + println() // val parsedFiles: List> = filesToProcess // .mapNotNull { f -> @@ -126,7 +135,7 @@ object Main2 { // } val outputDirectory = File(cmd.getOptionValue('o')) - println("Cleaning up output directory \"$outputDirectory\" before printing") + logger.info("Cleaning up output directory \"$outputDirectory\" before printing") outputDirectory.deleteRecursively() translatedFiles.forEach { (file, eoProgram) -> @@ -143,11 +152,14 @@ object Main2 { file.name.replace(".java", ".eo") ) - println("Printing output to file $outputFile") + if (cmd.hasOption("d")) { + logger.debug("Printing output to file $outputFile") + } outputPath.createDirectories() Files.writeString(Files.createFile(outputFile), targetText) } + logger.info("Translation complete.") // Resource // InputStream = javaClass.getResourceAsStream() } From a3fbc2160380707140d9cdece82b93a67577fc02 Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Tue, 19 Apr 2022 22:39:38 +0300 Subject: [PATCH 03/29] New stdlib, dynamic support for all primitives, fixed imports, fixed generation of arithmetic expressions --- src/main/java/translator/Declarations.kt | 28 +- src/main/java/translator/Literals.kt | 21 +- src/main/java/translator/Translator.kt | 9 +- .../translator/preprocessor/Preprocessor.kt | 42 +- src/main/java/util/PrimitiveTypesFinder.kt | 18 +- src/main/java/util/TokenCodes.kt | 28 +- src/main/resources/stdlib/case.eo | 4 - src/main/resources/stdlib/class__Boolean.eo | 69 ---- src/main/resources/stdlib/class__Float.eo | 212 ---------- src/main/resources/stdlib/class__Integer.eo | 329 --------------- .../resources/stdlib/class__PrintStream.eo | 42 -- src/main/resources/stdlib/class__String.eo | 73 ---- src/main/resources/stdlib/default.eo | 9 - .../resources/stdlib/io/class__PrintStream.eo | 34 ++ .../stdlib/{ => lang}/class__Object.eo | 16 +- .../resources/stdlib/lang/class__String.eo | 72 ++++ .../stdlib/{ => lang}/class__System.eo | 20 +- src/main/resources/stdlib/prim__boolean.eo | 75 ---- src/main/resources/stdlib/prim__float.eo | 278 ------------- src/main/resources/stdlib/prim__int.eo | 384 ------------------ src/main/resources/stdlib/prim__number.eo | 28 -- .../stdlib/primitives/prim__boolean.eo | 81 ++++ .../resources/stdlib/primitives/prim__byte.eo | 116 ++++++ .../resources/stdlib/primitives/prim__char.eo | 116 ++++++ .../stdlib/primitives/prim__double.eo | 116 ++++++ .../stdlib/primitives/prim__float.eo | 116 ++++++ .../resources/stdlib/primitives/prim__int.eo | 133 ++++++ .../resources/stdlib/primitives/prim__num.eo | 81 ++++ .../stdlib/primitives/prim__short.eo | 116 ++++++ .../resources/stdlib/primitives/prin__long.eo | 116 ++++++ src/main/resources/stdlib/switch.eo | 4 - src/test/resources/test_ready/SimpleTest.java | 2 + 32 files changed, 1197 insertions(+), 1591 deletions(-) delete mode 100644 src/main/resources/stdlib/case.eo delete mode 100644 src/main/resources/stdlib/class__Boolean.eo delete mode 100644 src/main/resources/stdlib/class__Float.eo delete mode 100644 src/main/resources/stdlib/class__Integer.eo delete mode 100644 src/main/resources/stdlib/class__PrintStream.eo delete mode 100644 src/main/resources/stdlib/class__String.eo delete mode 100644 src/main/resources/stdlib/default.eo create mode 100644 src/main/resources/stdlib/io/class__PrintStream.eo rename src/main/resources/stdlib/{ => lang}/class__Object.eo (52%) create mode 100644 src/main/resources/stdlib/lang/class__String.eo rename src/main/resources/stdlib/{ => lang}/class__System.eo (56%) delete mode 100644 src/main/resources/stdlib/prim__boolean.eo delete mode 100644 src/main/resources/stdlib/prim__float.eo delete mode 100644 src/main/resources/stdlib/prim__int.eo delete mode 100644 src/main/resources/stdlib/prim__number.eo create mode 100644 src/main/resources/stdlib/primitives/prim__boolean.eo create mode 100644 src/main/resources/stdlib/primitives/prim__byte.eo create mode 100644 src/main/resources/stdlib/primitives/prim__char.eo create mode 100644 src/main/resources/stdlib/primitives/prim__double.eo create mode 100644 src/main/resources/stdlib/primitives/prim__float.eo create mode 100644 src/main/resources/stdlib/primitives/prim__int.eo create mode 100644 src/main/resources/stdlib/primitives/prim__num.eo create mode 100644 src/main/resources/stdlib/primitives/prim__short.eo create mode 100644 src/main/resources/stdlib/primitives/prin__long.eo delete mode 100644 src/main/resources/stdlib/switch.eo diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index 13a9c828..1d70ed21 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -47,7 +47,13 @@ fun preMapVariableDeclaration(dec: VariableDeclaration): EOBndExpr = is TypeName -> EOBndExpr(EODot("cage"), dec.name) is PrimitiveType -> - EOBndExpr(listOf(decodePrimitiveType(dec.type as PrimitiveType), decodeInitializer(dec.initializer)).eoDot(), dec.name) + EOBndExpr( + EOCopy( + listOf(decodePrimitiveType(dec.type as PrimitiveType).value, decodeInitializer(dec.initializer)).eoDot(), + listOf(decodePrimitiveType(dec.type as PrimitiveType).value, "new").eoDot() + ), + dec.name + ) null -> throw IllegalArgumentException("\"var\" declarations are not supported yet") else -> @@ -71,20 +77,20 @@ fun mapVariableDeclaration(parseExprTasks: ParseExprTasks, dec: VariableDeclarat throw IllegalArgumentException("Type of type " + dec.type.javaClass.name + " is not supported") } -fun decodePrimitiveType(type: PrimitiveType): String { +fun decodePrimitiveType(type: PrimitiveType): TokenCodes { return when (type.typeCode) { - TokenCode.Char -> TokenCodes.PRIM__CHAR.value - TokenCode.Int -> TokenCodes.PRIM__INT.value - TokenCode.Float -> TokenCodes.PRIM__FLOAT.value - TokenCode.Double -> TokenCodes.PRIM__DOUBLE.value - TokenCode.Boolean -> TokenCodes.PRIM__BOOLEAN.value - TokenCode.Long -> TokenCodes.PRIM__LONG.value - TokenCode.Byte -> TokenCodes.PRIM__BYTE.value - TokenCode.Short -> TokenCodes.PRIM__SHORT.value + TokenCode.Char -> TokenCodes.PRIM__CHAR + TokenCode.Int -> TokenCodes.PRIM__INT + TokenCode.Float -> TokenCodes.PRIM__FLOAT + TokenCode.Double -> TokenCodes.PRIM__DOUBLE + TokenCode.Boolean -> TokenCodes.PRIM__BOOLEAN + TokenCode.Long -> TokenCodes.PRIM__LONG + TokenCode.Byte -> TokenCodes.PRIM__BYTE + TokenCode.Short -> TokenCodes.PRIM__SHORT else -> throw IllegalArgumentException("Type code " + type.typeCode + " is not supported") } } fun decodeInitializer(initializer: Initializer?): String { - return "constructor1" + return "constructor_1" } diff --git a/src/main/java/translator/Literals.kt b/src/main/java/translator/Literals.kt index 1ee49797..7d9c6dd3 100644 --- a/src/main/java/translator/Literals.kt +++ b/src/main/java/translator/Literals.kt @@ -12,33 +12,39 @@ import util.TokenCodes fun mapLiteral(literal: Literal): EOObject = when (literal.code) { TokenCode.StringLiteral -> generateEOData( - listOf(TokenCodes.CLASS__STRING.value, "constructor2").eoDot(), + listOf(TokenCodes.CLASS__STRING.value, "constructor_2").eoDot(), + listOf(TokenCodes.CLASS__STRING.value, "new").eoDot(), EOStringData(literal.value as String) ) TokenCode.FloatingLiteral -> generateEOData( - listOf(TokenCodes.PRIM__FLOAT.value, "constructor2").eoDot(), + listOf(TokenCodes.PRIM__FLOAT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__FLOAT.value, "new").eoDot(), EOFloatData((literal.value as String).toFloat()) ) TokenCode.IntegerLiteral -> generateEOData( - listOf(TokenCodes.PRIM__INT.value, "constructor2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), EOIntData(try {(literal.value as String).toInt()} catch (e: NumberFormatException) { 0 /* FIXME: parse integer literals */ }) ) TokenCode.True -> generateEOData( - listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), EOBoolData(true) ) TokenCode.False -> generateEOData( - listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), EOBoolData(false) ) TokenCode.Null -> generateEOData( /* FIXME: use proper null */ - listOf(TokenCodes.PRIM__INT.value, "constructor2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), EOIntData(0) ) else -> throw IllegalArgumentException("Mapping of type ${literal.javaClass.simpleName} (${literal.code}) is not supported.") } -fun generateEOData(primitiveTypeCall: EODot, value: EOData) : EOObject = +fun generateEOData(primitiveTypeCall: EODot, primitiveNewCall: EODot, value: EOData) : EOObject = EOObject( listOf(), None, @@ -46,6 +52,7 @@ fun generateEOData(primitiveTypeCall: EODot, value: EOData) : EOObject = EOBndExpr( EOCopy( primitiveTypeCall, + primitiveNewCall, value ), "@" diff --git a/src/main/java/translator/Translator.kt b/src/main/java/translator/Translator.kt index 832f0eed..fbb01434 100644 --- a/src/main/java/translator/Translator.kt +++ b/src/main/java/translator/Translator.kt @@ -9,13 +9,10 @@ import tree.Compilation.CompilationUnit import tree.Compilation.Package import tree.Compilation.SimpleCompilationUnit import tree.Compilation.TopLevelComponent -import tree.Entity import util.findMainClass import util.generateEntryPoint -import util.logger import java.time.LocalDateTime import java.util.* -import kotlin.streams.toList class Translator { @@ -64,10 +61,10 @@ class Translator { // FIXME: assuming there is only one top-level component and it is a class // Always calling the 'main' method - val stdAliases = preprocessorState.stdClassesForCurrentAlias.stream() - .map { EOMeta("alias", "stdlib.$it") }.toList() + val stdAliases = preprocessorState.stdTokensForCurrentAlias.stream() + .map { EOMeta("alias", it) }.toList() val eoAliases = preprocessorState.eoClassesForCurrentAlias.stream() - .map { EOMeta("alias", "org.eolang.$it") }.toList() + .map { EOMeta("alias", it) }.toList() return EOProgram( EOLicense( diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index d55db6ad..4c8ae4f3 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -23,28 +23,30 @@ import kotlin.collections.HashSet /** * @property classNames - * @property stdClassesNeededForAlias - * @property stdClassesForCurrentAlias + * @property stdTokensNeededForAlias + * @property stdTokensForCurrentAlias */ data class PreprocessorState( val classNames: HashMap = hashMapOf( - "Object" to TokenCodes.CLASS__OBJECT.value, - "System" to TokenCodes.CLASS__SYSTEM.value, - "int" to TokenCodes.PRIM__INT.value, - "float" to TokenCodes.PRIM__FLOAT.value, - "boolean" to TokenCodes.PRIM__BOOLEAN.value, + "Object" to TokenCodes.CLASS__OBJECT.value, + "System" to TokenCodes.CLASS__SYSTEM.value, ), - val stdClassesNeededForAlias: HashSet = hashSetOf( - TokenCodes.CLASS__OBJECT.value, - TokenCodes.CLASS__SYSTEM.value, - TokenCodes.PRIM__INT.value, - TokenCodes.PRIM__FLOAT.value, - TokenCodes.PRIM__BOOLEAN.value, - TokenCodes.CLASS__STRING.value, - TokenCodes.EO_CAGE.value + val stdTokensNeededForAlias: HashSet = hashSetOf( + TokenCodes.CLASS__OBJECT.value, + TokenCodes.CLASS__SYSTEM.value, + TokenCodes.PRIM__INT.value, + TokenCodes.PRIM__FLOAT.value, + TokenCodes.PRIM__BOOLEAN.value, + TokenCodes.CLASS__STRING.value, + TokenCodes.EO_CAGE.value, + TokenCodes.PRIM__LONG.value, + TokenCodes.PRIM__BYTE.value, + TokenCodes.PRIM__CHAR.value, + TokenCodes.PRIM__DOUBLE.value, + TokenCodes.PRIM__SHORT.value ), - val stdClassesForCurrentAlias: HashSet = hashSetOf( - TokenCodes.CLASS__OBJECT.value // We need it always + val stdTokensForCurrentAlias: HashSet = hashSetOf( + TokenCodes.CLASS__OBJECT.importPath // We need it always ), val eoClassesForCurrentAlias: HashSet = hashSetOf() ) @@ -114,7 +116,7 @@ private fun preprocessSimpleCompilationUnit(state: PreprocessorState, unit: Simp } collectClassNames(unit) - collectPrimitivePackages(state.stdClassesForCurrentAlias, unit) + collectPrimitivePackages(state.stdTokensForCurrentAlias, unit) unit.components.components .map { component: TopLevelComponent? -> preprocessTopLevelComponent(state, component!!) } @@ -259,9 +261,9 @@ private fun preprocessCompoundName(state: PreprocessorState, compoundName: Compo } private fun tryAddClassForAliases(state: PreprocessorState, className: String, forStdLib: Boolean = true) { - if (state.stdClassesNeededForAlias.contains(className)) { + if (state.stdTokensNeededForAlias.contains(className)) { if (forStdLib) { - state.stdClassesForCurrentAlias.add(className) + state.stdTokensForCurrentAlias.add(className) } else { state.eoClassesForCurrentAlias.add(className) } diff --git a/src/main/java/util/PrimitiveTypesFinder.kt b/src/main/java/util/PrimitiveTypesFinder.kt index ffdfa103..d8d01929 100644 --- a/src/main/java/util/PrimitiveTypesFinder.kt +++ b/src/main/java/util/PrimitiveTypesFinder.kt @@ -24,11 +24,13 @@ private fun findPrimitivesInMethodInvocation(primitives: HashSet, method ?.map { findPrimitivesInExpression(primitives, it) } } -private fun decodeLiteralCode(code: TokenCode): String? { +private fun decodeLiteralCode(code: TokenCode): TokenCodes? { return when(code) { - TokenCode.IntegerLiteral -> TokenCodes.PRIM__INT.value - TokenCode.FloatingLiteral -> TokenCodes.PRIM__FLOAT.value - TokenCode.StringLiteral -> TokenCodes.CLASS__STRING.value + TokenCode.IntegerLiteral -> TokenCodes.PRIM__INT + TokenCode.FloatingLiteral -> TokenCodes.PRIM__FLOAT + TokenCode.StringLiteral -> TokenCodes.CLASS__STRING + TokenCode.False -> TokenCodes.PRIM__BOOLEAN + TokenCode.True -> TokenCodes.PRIM__BOOLEAN else -> null } } @@ -36,7 +38,7 @@ private fun decodeLiteralCode(code: TokenCode): String? { private fun findPrimitivesInLiteral(primitives: HashSet, literal: Literal) { val primitiveType = decodeLiteralCode(literal.code) if (primitiveType != null) { - primitives.add(primitiveType) + primitives.add(primitiveType.importPath) } } @@ -46,6 +48,8 @@ private fun findPrimitivesInExpression(primitives: HashSet, expr: Expres is Literal -> findPrimitivesInLiteral(primitives, expr) is Binary -> findPrimitivesInExpression(primitives, expr.right) is Parenthesized -> findPrimitivesInExpression(primitives, expr.expression) + is UnaryPrefix -> findPrimitivesInExpression(primitives, expr.operand) + is UnaryPostfix -> findPrimitivesInExpression(primitives, expr.operand) } } @@ -72,11 +76,11 @@ private fun findPrimitivesInMethod(primitives: HashSet, methodDecl: Meth private fun findPrimitivesInVarDeclaration(primitives: HashSet, varDeclType: Type) { if (varDeclType is PrimitiveType) { - primitives.add(decodePrimitiveType(varDeclType)) + primitives.add(decodePrimitiveType(varDeclType).importPath) } else if (varDeclType is TypeName && varDeclType.compoundName.names.size == 1 && varDeclType.compoundName.names.last().equals("String")) { - primitives.add(TokenCodes.CLASS__STRING.value) + primitives.add(TokenCodes.CLASS__STRING.importPath) } } diff --git a/src/main/java/util/TokenCodes.kt b/src/main/java/util/TokenCodes.kt index b9b94c8f..af3c8d55 100644 --- a/src/main/java/util/TokenCodes.kt +++ b/src/main/java/util/TokenCodes.kt @@ -1,17 +1,17 @@ package util -enum class TokenCodes(val value: String) { - PRIM__BYTE("prim__byte"), - PRIM__SHORT("prim__short"), - PRIM__CHAR("prim__char"), - PRIM__INT("prim__int"), - PRIM__LONG("prim__long"), - PRIM__FLOAT("prim__float"), - PRIM__DOUBLE("prim__double"), - PRIM__BOOLEAN("prim__boolean"), - PRIM__NUMBER("prim__number"), - CLASS__SYSTEM("class__System"), - CLASS__STRING("class__String"), - CLASS__OBJECT("class__Object"), - EO_CAGE("gray.cage") +enum class TokenCodes(val value: String, val importPath: String) { + PRIM__BYTE("prim__byte", "stdlib.primitives.prim__byte"), + PRIM__SHORT("prim__short", "stdlib.primitives.prim__short"), + PRIM__CHAR("prim__char", "stdlib.primitives.prim__char"), + PRIM__INT("prim__int", "stdlib.primitives.prim__int"), + PRIM__LONG("prim__long", "stdlib.primitives.prim__long"), + PRIM__FLOAT("prim__float", "stdlib.primitives.prim__float"), + PRIM__DOUBLE("prim__double", "stdlib.primitives.prim__double"), + PRIM__BOOLEAN("prim__boolean", "stdlib.primitives.prim__boolean"), + PRIM__NUMBER("prim__number", "stdlib.primitives.prim__number"), + CLASS__SYSTEM("class__System", "stdlib.lang.class__System"), + CLASS__STRING("class__String", "stdlib.lang.class__String"), + CLASS__OBJECT("class__Object", "stdlib.lang.class__Object"), + EO_CAGE("gray.cage", "org.eolang.gray.cage") } \ No newline at end of file diff --git a/src/main/resources/stdlib/case.eo b/src/main/resources/stdlib/case.eo deleted file mode 100644 index c680b426..00000000 --- a/src/main/resources/stdlib/case.eo +++ /dev/null @@ -1,4 +0,0 @@ -+package stdlib - -[v a] > case - TRUE > is-case diff --git a/src/main/resources/stdlib/class__Boolean.eo b/src/main/resources/stdlib/class__Boolean.eo deleted file mode 100644 index d22ab3f2..00000000 --- a/src/main/resources/stdlib/class__Boolean.eo +++ /dev/null @@ -1,69 +0,0 @@ -+package stdlib -+alias stdlib.class__Object -+alias stdlib.class__String - -[] > class__Boolean - class__Object > super - super > @ - - [] > new - [] > this - "class__Boolean" > className - class__Object.new > super - super > @ - - memory > v - - [self t] > init - seq > @ - self.v.write - t - - [self] > toString - seq > @ - class__String.constructor2 - if. - self.v - "true" - "false" - - [] > not - seq > @ - class__Boolean.constructor2 - ^.v.not - - [right] > and - seq > @ - class__Boolean.constructor2 - ^.v.and - right.v - - [right] > or - seq > @ - class__Boolean.constructor2 - ^.v.or - right.v - - seq > @ - this - - [] > constructor1 - new > self - seq > @ - self - - [t] > constructor2 - new > self - seq > @ - self.init - self - t - self - - [i_o] > constructor3 - new > self - seq > @ - self.init - self - i_o.v - self diff --git a/src/main/resources/stdlib/class__Float.eo b/src/main/resources/stdlib/class__Float.eo deleted file mode 100644 index c2767053..00000000 --- a/src/main/resources/stdlib/class__Float.eo +++ /dev/null @@ -1,212 +0,0 @@ -+package stdlib -+alias stdlib.class__Object -+alias stdlib.class__String -+alias stdlib.class__Boolean - -[] > class__Float - class__Object > super - super > @ - - [] > new - [] > this - "class__Float" > className - class__Object.new > super - super > @ - - memory > v - - [self t] > init - seq > @ - self.v.write - t - - [self] > toString - seq > @ - class__String.constructor2 - self.v.as-string - - [] > inc_post - class__Float.constructor1 > old - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - 1.0 - old - - [] > dec_post - class__Float.constructor1 > old - seq > @ - old.v.write - ^.v - ^.v.write - sub. - ^.v - 1.0 - old - - [] > inc_pre - class__Float.constructor1 > old - seq > @ - ^.v.write - add. - ^.v - 1.0 - old.v.write - ^.v - old - - [] > dec_pre - class__Float.constructor1 > old - seq > @ - ^.v.write - sub. - ^.v - 1.0 - old.v.write - ^.v - old - - [] > neg - seq > @ - class__Float.constructor2 - ^.v.neg - - [right] > write - seq > @ - ^.v.write - right.v - class__Float.constructor3 - ^ - - [right] > add - seq > @ - class__Float.constructor2 - add. - ^.v - right.v - - [right] > sub - seq > @ - class__Float.constructor2 - sub. - ^.v - right.v - - [right] > mul - seq > @ - class__Float.constructor2 - mul. - ^.v - right.v - - [right] > div - seq > @ - class__Float.constructor2 - div. - ^.v - right.v - - [right] > add_equal - seq > @ - ^.v.write - add. - ^.v - right.v - class__Float.constructor3 - ^ - - [right] > sub_equal - seq > @ - ^.v.write - sub. - ^.v - right.v - class__Float.constructor3 - ^ - - [right] > mul_equal - seq > @ - ^.v.write - mul. - ^.v - right.v - class__Float.constructor3 - ^ - - [right] > div_equal - seq > @ - ^.v.write - div. - ^.v - right.v - class__Float.constructor3 - ^ - - [right] > eq - seq > @ - class__Boolean.constructor2 - eq. - ^.v - right.v - - [right] > neq - seq > @ - class__Boolean.constructor2 - neq. - ^.v - right.v - - [right] > less - seq > @ - class__Boolean.constructor2 - less. - ^.v - right.v - - [right] > leq - seq > @ - class__Boolean.constructor2 - leq. - ^.v - right.v - - [right] > greater - seq > @ - class__Boolean.constructor2 - greater. - ^.v - right.v - - [right] > geq - seq > @ - class__Boolean.constructor2 - geq. - ^.v - right.v - - seq > @ - this - - [] > constructor1 - new > self - seq > @ - self - - [t] > constructor2 - new > self - seq > @ - self.init - self - t - self - - [i_o] > constructor3 - new > self - seq > @ - self.init - self - i_o.v - self diff --git a/src/main/resources/stdlib/class__Integer.eo b/src/main/resources/stdlib/class__Integer.eo deleted file mode 100644 index 8b02177b..00000000 --- a/src/main/resources/stdlib/class__Integer.eo +++ /dev/null @@ -1,329 +0,0 @@ -+package stdlib -+alias stdlib.class__Object -+alias stdlib.class__String -+alias stdlib.class__Boolean - -[] > class__Integer - class__Object > super - super > @ - - [] > new - [] > this - "class__Integer" > className - class__Object.new > super - super > @ - - memory > v - - [self t] > init - seq > @ - self.v.write - t - - [self] > toString - seq > @ - class__String.constructor2 - self.v.as-string - - [] > inc_post - class__Integer.constructor1 > old - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - 1 - old - - [] > dec_post - class__Integer.constructor1 > old - seq > @ - old.v.write - ^.v - ^.v.write - sub. - ^.v - 1 - old - - [] > inc_pre - class__Integer.constructor1 > old - seq > @ - ^.v.write - add. - ^.v - 1 - old.v.write - ^.v - old - - [] > dec_pre - class__Integer.constructor1 > old - seq > @ - ^.v.write - sub. - ^.v - 1 - old.v.write - ^.v - old - - [] > neg - seq > @ - class__Integer.constructor2 - ^.v.neg - - [right] > write - seq > @ - ^.v.write - right.v - class__Integer.constructor3 - ^ - - [right] > add - seq > @ - class__Integer.constructor2 - add. - ^.v - right.v - - [right] > sub - seq > @ - class__Integer.constructor2 - sub. - ^.v - right.v - - [right] > mul - seq > @ - class__Integer.constructor2 - mul. - ^.v - right.v - - [right] > div - seq > @ - class__Integer.constructor2 - div. - ^.v - right.v - - [right] > mod - seq > @ - class__Integer.constructor2 - mod. - ^.v - right.v - - [right] > add_equal - seq > @ - ^.v.write - add. - ^.v - right.v - class__Integer.constructor3 - ^ - - [right] > sub_equal - seq > @ - ^.v.write - sub. - ^.v - right.v - class__Integer.constructor3 - ^ - - [right] > mul_equal - seq > @ - ^.v.write - mul. - ^.v - right.v - class__Integer.constructor3 - ^ - - [right] > div_equal - seq > @ - ^.v.write - div. - ^.v - right.v - class__Integer.constructor3 - ^ - - [right] > mod_equal - seq > @ - ^.v.write - mod. - ^.v - right.v - class__Integer.constructor3 - ^ - - [right] > eq - seq > @ - class__Boolean.constructor2 - eq. - ^.v - right.v - - [right] > neq - seq > @ - class__Boolean.constructor2 - neq. - ^.v - right.v - - [right] > less - seq > @ - class__Boolean.constructor2 - less. - ^.v - right.v - - [right] > leq - seq > @ - class__Boolean.constructor2 - leq. - ^.v - right.v - - [right] > greater - seq > @ - class__Boolean.constructor2 - greater. - ^.v - right.v - - [right] > geq - seq > @ - class__Boolean.constructor2 - geq. - ^.v - right.v - - [right_v] > shift_r - seq > @ - class__Integer.constructor2 - ^.v.div - pow. - 2 - right_v.v - - [right_v] > shift_l - seq > @ - class__Integer.constructor2 - ^.v.mul - pow. - 2 - right_v.v - - [right_v] > shift_u - [] > less_0 - class__Integer.constructor2 > @ - div. - add. - 2147483647 - add. - div. - sub. - ^.^.v - 1 - 2 - 1 - pow. - 2 - sub. - right_v.v - 1 - [] > geq_0 - ^.^.shift_r > @ - ^.right_v - seq > @ - if. - less. - ^.v - 0 - less_0 - geq_0 - - [right_v] > shift_r_equal - seq > @ - ^.v.write - ^.v.div - pow. - 2 - right_v.v - class__Integer.constructor3 - ^ - - [right_v] > shift_l_equal - seq > @ - ^.v.write - ^.v.mul - pow. - 2 - right_v.v - class__Integer.constructor3 - ^ - - [right_v] > shift_u_equal - seq > @ - ^.write - ^.shift_u - right_v - class__Integer.constructor3 - ^ - - [right] > bit_and - seq > @ - class__Integer.constructor2 - as-int. - as-bytes. - ^.v - - [right] > bit_or - seq > @ - class__Integer.constructor2 - as-int. - as-bytes. - ^.v - - [right] > bit_xor - seq > @ - class__Integer.constructor2 - as-int. - as-bytes. - ^.v - - [] > bit_not - seq > @ - class__Integer.constructor2 - as-int. - as-bytes. - ^.v - - seq > @ - this - - [] > constructor1 - new > self - seq > @ - self - - [t] > constructor2 - new > self - seq > @ - self.init - self - t - self - - [i_o] > constructor3 - new > self - seq > @ - self.init - self - i_o.v - self diff --git a/src/main/resources/stdlib/class__PrintStream.eo b/src/main/resources/stdlib/class__PrintStream.eo deleted file mode 100644 index 6925fd57..00000000 --- a/src/main/resources/stdlib/class__PrintStream.eo +++ /dev/null @@ -1,42 +0,0 @@ -+package stdlib -+alias stdlib.class__Object -+alias stdout org.eolang.io.stdout - -[] > class__PrintStream - class__Object > super - super > @ - - [] > new - [] > this - "class__PrintStream" > className - class__Object.new > super - super > @ - - [self] > init - 0 > @ - - [self x] > println - [] > prim - x.as-string > @ - [] > non-prim - s. > @ - ^.x.toString - ^.x - seq > @ - stdout - if. - x.is-prim - prim - non-prim - stdout - "\n" - - seq > @ - this - - [] > constructor - new > self - seq > @ - self.init - self - self diff --git a/src/main/resources/stdlib/class__String.eo b/src/main/resources/stdlib/class__String.eo deleted file mode 100644 index c5b81b41..00000000 --- a/src/main/resources/stdlib/class__String.eo +++ /dev/null @@ -1,73 +0,0 @@ -+package stdlib -+alias stdlib.class__Object -+alias org.eolang.txt.sprintf - -[] > class__String - class__Object > super - super > @ - - [] > new - [] > this - "class__String" > className - class__Object.new > super - super > @ - - memory > s - - [self t] > init - seq > @ - self.s.write - t - - [self] > toString - seq > @ - class__String.constructor3 - self - - [right] > write - seq > @ - ^.s.write - right.s - class__String.constructor3 - ^ - - [right] > add - seq > @ - if. - right.is-prim - class__String.constructor2 - sprintf - "%s%s" - ^.s - right.as-string - class__String.constructor2 - sprintf - "%s%s" - ^.s - s. - right.toString - right - - seq > @ - this - - [] > constructor1 - new > self - seq > @ - self - - [t] > constructor2 - new > self - seq > @ - self.init - self - t - self - - [s_o] > constructor3 - new > self - seq > @ - self.init - self - s_o.s - self diff --git a/src/main/resources/stdlib/default.eo b/src/main/resources/stdlib/default.eo deleted file mode 100644 index 8e548c13..00000000 --- a/src/main/resources/stdlib/default.eo +++ /dev/null @@ -1,9 +0,0 @@ -+package stdlib -+alias stdlib.case - -[a] > default - case > @ - 0 - a - - FALSE > is-case diff --git a/src/main/resources/stdlib/io/class__PrintStream.eo b/src/main/resources/stdlib/io/class__PrintStream.eo new file mode 100644 index 00000000..e90e6bb9 --- /dev/null +++ b/src/main/resources/stdlib/io/class__PrintStream.eo @@ -0,0 +1,34 @@ ++package stdlib.io ++alias stdlib.lang.class__Object ++alias org.eolang.io.stdout + +[] > class__PrintStream + class__Object > super + super > @ + + [] > new + [] > this + class__Object.new > super + super > @ + "class__PrintStream" > className + + [this] > init + 0 > @ + + [this output] > println + seq > @ + stdout + str. + output.toString + output + stdout + "\n" + + seq > @ + this + + [this] > constructor + seq > @ + this.init + this + this diff --git a/src/main/resources/stdlib/class__Object.eo b/src/main/resources/stdlib/lang/class__Object.eo similarity index 52% rename from src/main/resources/stdlib/class__Object.eo rename to src/main/resources/stdlib/lang/class__Object.eo index e470c723..d13eccda 100644 --- a/src/main/resources/stdlib/class__Object.eo +++ b/src/main/resources/stdlib/lang/class__Object.eo @@ -1,24 +1,22 @@ -+package stdlib ++package stdlib.lang [] > class__Object [] > new [] > this - FALSE > is-prim "class__Object" > className "OBJECT" > @ - [self] > init + [this] > init 0 > @ - [self] > toString + [this] > toString "OBJECT" > @ seq > @ this - [] > constructor - new > self + [this] > constructor seq > @ - self.init - self - self + this.init + this + this diff --git a/src/main/resources/stdlib/lang/class__String.eo b/src/main/resources/stdlib/lang/class__String.eo new file mode 100644 index 00000000..e152b6f1 --- /dev/null +++ b/src/main/resources/stdlib/lang/class__String.eo @@ -0,0 +1,72 @@ ++package stdlib.lang ++alias stdlib.lang.class__Object ++alias org.eolang.txt.sprintf + +[] > class__String + class__Object > super + super > @ + + [] > new + [] > this + class__Object.new > super + super > @ + "class__String" > className + + memory > str + + [this input_string] > init + seq > @ + this.str.write + input_string + + [this] > toString + seq > @ + class__String.constructor_3 + class__String.new + this + + [right] > write + seq > @ + ^.str.write + right.str + class__String.constructor_3 + class__String.new + ^ + + [right] > add + seq > @ + class__String.constructor_2 + class__String.new + sprintf + "%s%s" + ^.str + str. + right.toString + right + + seq > @ + this + + [right] > valueOf + seq > @ + class__String.constructor_2 + class__String.new + right.as-string + + [this] > constructor_1 + seq > @ + this + + [this target] > constructor_2 + seq > @ + this.init + this + target + this + + [this another_string] > constructor_3 + seq > @ + this.init + this + another_string.str + this diff --git a/src/main/resources/stdlib/class__System.eo b/src/main/resources/stdlib/lang/class__System.eo similarity index 56% rename from src/main/resources/stdlib/class__System.eo rename to src/main/resources/stdlib/lang/class__System.eo index 66133e14..1418776b 100644 --- a/src/main/resources/stdlib/class__System.eo +++ b/src/main/resources/stdlib/lang/class__System.eo @@ -1,28 +1,28 @@ -+package stdlib -+alias stdlib.class__Object -+alias stdlib.class__PrintStream ++package stdlib.lang ++alias stdlib.lang.class__Object ++alias stdlib.io.class__PrintStream [] > class__System class__Object > super super > @ class__PrintStream.constructor > out + class__PrintStream.new [] > new [] > this - "class__System" > className class__Object.new > super super > @ + "class__System" > className - [self] > init + [this] > init 0 > @ seq > @ this - [] > constructor - new > self + [this] > constructor seq > @ - self.init - self - self + this.init + this + this diff --git a/src/main/resources/stdlib/prim__boolean.eo b/src/main/resources/stdlib/prim__boolean.eo deleted file mode 100644 index ed277f1a..00000000 --- a/src/main/resources/stdlib/prim__boolean.eo +++ /dev/null @@ -1,75 +0,0 @@ -+package stdlib - -[] > prim__boolean - [] > new - [] > this - "prim__boolean" > primName - TRUE > is-prim - "BOOLEAN" > @ - - memory > v - - [self t] > init - seq > @ - self.v.write - t - - [right] > write - seq > @ - if. - right.primName.eq - "prim__boolean" - seq - ^.v.write - right.v - ^ - [] - "error: incompatible types: possible lossy conversion from double to boolean" > msg - - [] > as-string - seq > @ - if. - ^.v - "true" - "false" - - [] > not - seq > @ - prim__boolean.constructor2 - ^.v.not - - [right] > and - seq > @ - prim__boolean.constructor2 - ^.v.and - right.v - - [right] > or - seq > @ - prim__boolean.constructor2 - ^.v.or - right.v - - seq > @ - this - - [] > constructor1 - new > self - seq > @ - self - - [t] > constructor2 - new > self - seq > @ - self.init - self - t - self - - [b] > constructor3 - new > self - seq > @ - self.init - self - b.v - self diff --git a/src/main/resources/stdlib/prim__float.eo b/src/main/resources/stdlib/prim__float.eo deleted file mode 100644 index 299d5613..00000000 --- a/src/main/resources/stdlib/prim__float.eo +++ /dev/null @@ -1,278 +0,0 @@ -+package stdlib -+alias stdlib.prim__number -+alias stdlib.prim__boolean - -[] > prim__float - [is_left] > new - [] > right_v - "prim__float" > primName - prim__number.new > @ - ^.is_left - - [right] > add - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - add. - ^.v - right.v - prim__float.constructor2 - add. - ^.v - right.v.as-float - - [right] > sub - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - sub. - ^.v - right.v - prim__float.constructor2 - sub. - ^.v - right.v.as-float - - [right] > mul - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - mul. - ^.v - right.v - prim__float.constructor2 - mul. - ^.v - right.v.as-float - - [right] > div - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - div. - ^.v - right.v - prim__float.constructor2 - div. - ^.v - right.v.as-float - - [] > neg - seq > @ - prim__float.constructor2 - ^.v.neg - - [right] > eq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - eq. - ^.v - right.v - prim__boolean.constructor2 - eq. - ^.v - right.v.as-float - - [right] > neq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - neq. - ^.v - right.v - prim__boolean.constructor2 - neq. - ^.v - right.v.as-float - - [right] > less - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - less. - ^.v - right.v - prim__boolean.constructor2 - less. - ^.v - right.v.as-float - - [right] > leq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - leq. - ^.v - right.v - prim__boolean.constructor2 - leq. - ^.v - right.v.as-float - - [right] > greater - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - greater. - ^.v - right.v - prim__boolean.constructor2 - greater. - ^.v - right.v.as-float - - [right] > geq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - geq. - ^.v - right.v - prim__boolean.constructor2 - geq. - ^.v - right.v.as-float - - [] > this - right_v > @ - - [right] > write - seq > @ - if. - right.primName.eq - "prim__float" - seq - ^.v.write - right.v - ^ - seq - ^.v.write - right.v.as-float - ^ - - [right] > add_equal - seq > @ - ^.write - ^.add - right - ^ - - [right] > sub_equal - seq > @ - ^.write - ^.sub - right - ^ - - [right] > mul_equal - seq > @ - ^.write - ^.mul - right - ^ - - [right] > div_equal - seq > @ - ^.write - ^.div - right - ^ - - [] > inc_post - prim__float.constructor2 > old - 0 - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - 1.0 - old - - [] > dec_post - prim__float.constructor2 > old - 0 - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - -1.0 - old - - [] > inc_pre - prim__float.constructor2 > old - 0 - seq > @ - ^.v.write - add. - ^.v - 1.0 - old.v.write - ^.v - old - - [] > dec_pre - prim__float.constructor2 > old - 0 - seq > @ - ^.v.write - add. - ^.v - -1.0 - old.v.write - ^.v - old - - seq > @ - if. - is_left - this - right_v - - [] > constructor1 - new > self - TRUE - seq > @ - self - - [t] > constructor2 - new > self - FALSE - seq > @ - self.init - self - t - self - - [i] > constructor3 - new > self - FALSE - seq > @ - self.init - self - i.v - self diff --git a/src/main/resources/stdlib/prim__int.eo b/src/main/resources/stdlib/prim__int.eo deleted file mode 100644 index b284177e..00000000 --- a/src/main/resources/stdlib/prim__int.eo +++ /dev/null @@ -1,384 +0,0 @@ -+package stdlib -+alias stdlib.prim__number -+alias stdlib.prim__float -+alias stdlib.prim__boolean - -[] > prim__int - [is_left] > new - [] > right_v - "prim__int" > primName - prim__number.new > @ - ^.is_left - - [right] > add - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - add. - ^.v.as-float - right.v - prim__int.constructor2 - add. - ^.v - right.v - - [right] > sub - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - sub. - ^.v.as-float - right.v - prim__int.constructor2 - sub. - ^.v - right.v - - [right] > mul - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - mul. - ^.v.as-float - right.v - prim__int.constructor2 - mul. - ^.v - right.v - - [right] > div - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - div. - ^.v.as-float - right.v - prim__int.constructor2 - div. - ^.v - right.v - - [right] > mod - seq > @ - if. - right_v.primName.eq - "prim__float" - prim__float.constructor2 - mod. - ^.v.as-float - right.v - prim__int.constructor2 - mod. - ^.v - right.v - - [] > neg - seq > @ - prim__int.constructor2 - ^.v.neg - - [right] > eq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - eq. - ^.v.as-float - right.v - prim__boolean.constructor2 - eq. - ^.v - right.v - - [right] > neq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - neq. - ^.v.as-float - right.v - prim__boolean.constructor2 - neq. - ^.v - right.v - - [right] > less - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - less. - ^.v.as-float - right.v - prim__boolean.constructor2 - less. - ^.v - right.v - - [right] > leq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - leq. - ^.v.as-float - right.v - prim__boolean.constructor2 - leq. - ^.v - right.v - - [right] > greater - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - greater. - ^.v.as-float - right.v - prim__boolean.constructor2 - greater. - ^.v - right.v - - [right] > geq - seq > @ - if. - right.primName.eq - "prim__float" - prim__boolean.constructor2 - geq. - ^.v.as-float - right.v - prim__boolean.constructor2 - geq. - ^.v - right.v - - [right] > shift_r - seq > @ - if. - right.v.geq - 0 - prim__int.constructor2 - ^.v.div - pow. - 2 - right.v - prim__int.constructor2 - 0 - - [right] > shift_l - seq > @ - if. - right.v.geq - 0 - prim__int.constructor2 - ^.v.mul - pow. - 2 - right.v - prim__int.constructor2 - 0 - - [right] > shift_u - [] > less_0 - prim__int.constructor2 > @ - div. - add. - 2147483647 - add. - div. - sub. - ^.^.v - 1 - 2 - 1 - pow. - 2 - sub. - right.v - 1 - [] > geq_0 - ^.^.shift_r > @ - ^.right - seq > @ - if. - right.v.geq - 0 - if. - right.v.greater - 0 - if. - less. - ^.v - 0 - less_0 - geq_0 - prim__int.constructor2 - ^.v - prim__int.constructor2 - 0 - - [] > this - right_v > @ - - [right] > write - seq > @ - if. - right.primName.eq - "prim__int" - seq - ^.v.write - right.v - ^ - [] - "error: incompatible types: possible lossy conversion from double to int" > msg - - [right] > add_equal - seq > @ - ^.write - ^.add - right - ^ - - [right] > sub_equal - seq > @ - ^.write - ^.sub - right - ^ - - [right] > mul_equal - seq > @ - ^.write - ^.mul - right - ^ - - [right] > div_equal - seq > @ - ^.write - ^.div - right - ^ - - [right] > mod_equal - seq > @ - ^.write - ^.mod - right - ^ - - [right] > shift_r_equal - seq > @ - ^.write - ^.shift_r - right - ^ - - [right] > shift_l_equal - seq > @ - ^.write - ^.shift_l - right - ^ - - [right] > shift_u_equal - seq > @ - ^.write - ^.shift_u - right - ^ - - [] > inc_post - prim__int.constructor2 > old - 0 - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - 1 - old - - [] > dec_post - prim__int.constructor2 > old - 0 - seq > @ - old.v.write - ^.v - ^.v.write - add. - ^.v - -1 - old - - [] > inc_pre - prim__int.constructor2 > old - 0 - seq > @ - ^.v.write - add. - ^.v - 1 - old.v.write - ^.v - old - - [] > dec_pre - prim__int.constructor2 > old - 0 - seq > @ - ^.v.write - add. - ^.v - -1 - old.v.write - ^.v - old - - seq > @ - if. - is_left - this - right_v - - [] > constructor1 - new > self - TRUE - seq > @ - self - - [t] > constructor2 - new > self - FALSE - seq > @ - self.init - self - t - self - - [i] > constructor3 - new > self - FALSE - seq > @ - self.init - self - i.v - self diff --git a/src/main/resources/stdlib/prim__number.eo b/src/main/resources/stdlib/prim__number.eo deleted file mode 100644 index c11f62f4..00000000 --- a/src/main/resources/stdlib/prim__number.eo +++ /dev/null @@ -1,28 +0,0 @@ -+package stdlib - -[] > prim__number - [is_left] > new - [] > right_v - TRUE > is-prim - "prim__number" > primName - "NUMBER" > @ - - memory > v - - [self t] > init - seq > @ - self.v.write - t - - [] > as-string - seq > @ - ^.v.as-string - - [] > this - right_v > @ - - seq > @ - if. - is_left - this - right_v diff --git a/src/main/resources/stdlib/primitives/prim__boolean.eo b/src/main/resources/stdlib/primitives/prim__boolean.eo new file mode 100644 index 00000000..e6065599 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__boolean.eo @@ -0,0 +1,81 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__boolean + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__boolean" > prim_name + + [] > as-string + seq > @ + if. + ^.v + "true" + "false" + + [right] > write + seq > @ + ^.v.write + right.v + prim__boolean.constructor_3 + prim__boolean.new + ^ + + [right] > and + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.and + right.v + + [right] > or + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.or + right.v + + [] > not + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.not + + [t_s f_s] > if + seq > @ + if. + ^.v + t_s + f_s + + [f] > while + seq > @ + while. + ^.v + f + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__byte.eo b/src/main/resources/stdlib/primitives/prim__byte.eo new file mode 100644 index 00000000..3f960777 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__byte.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__byte + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__byte" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__byte.constructor_3 + prim__byte.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__byte.constructor_3 + prim__byte.new + ^ + + [] > inc_post + prim__byte.constructor_1 > old + prim__byte.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__byte.constructor_1 > old + prim__byte.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__byte.constructor_3 + prim__byte.new + ^ + + [right] > add + seq > @ + prim__byte.constructor_2 + prim__byte.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__byte.constructor_2 + prim__byte.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__byte.constructor_2 + prim__byte.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__byte.constructor_2 + prim__byte.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__byte.constructor_2 + prim__byte.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__char.eo b/src/main/resources/stdlib/primitives/prim__char.eo new file mode 100644 index 00000000..9fb44508 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__char.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__char + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__char" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__char.constructor_3 + prim__char.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__char.constructor_3 + prim__char.new + ^ + + [] > inc_post + prim__char.constructor_1 > old + prim__char.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__char.constructor_1 > old + prim__char.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__char.constructor_3 + prim__char.new + ^ + + [right] > add + seq > @ + prim__char.constructor_2 + prim__char.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__char.constructor_2 + prim__char.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__char.constructor_2 + prim__char.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__char.constructor_2 + prim__char.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__char.constructor_2 + prim__char.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__double.eo b/src/main/resources/stdlib/primitives/prim__double.eo new file mode 100644 index 00000000..d33ed5ca --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__double.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__double + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__double" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__double.constructor_3 + prim__double.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__double.constructor_3 + prim__double.new + ^ + + [] > inc_post + prim__double.constructor_1 > old + prim__double.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__double.constructor_1 > old + prim__double.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__double.constructor_3 + prim__double.new + ^ + + [right] > add + seq > @ + prim__double.constructor_2 + prim__double.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__double.constructor_2 + prim__double.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__double.constructor_2 + prim__double.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__double.constructor_2 + prim__double.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__double.constructor_2 + prim__double.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__float.eo b/src/main/resources/stdlib/primitives/prim__float.eo new file mode 100644 index 00000000..0883ffd3 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__float.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__float + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__float" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__float.constructor_3 + prim__float.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__float.constructor_3 + prim__float.new + ^ + + [] > inc_post + prim__float.constructor_1 > old + prim__float.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__float.constructor_1 > old + prim__float.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__float.constructor_3 + prim__float.new + ^ + + [right] > add + seq > @ + prim__float.constructor_2 + prim__float.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__float.constructor_2 + prim__float.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__float.constructor_2 + prim__float.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__float.constructor_2 + prim__float.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__float.constructor_2 + prim__float.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__int.eo b/src/main/resources/stdlib/primitives/prim__int.eo new file mode 100644 index 00000000..b76af4a9 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__int.eo @@ -0,0 +1,133 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__int + prim__num > super + super > @ + 2147483647 > max_int + -2147483648 > min_int + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__int" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__int.constructor_3 + prim__int.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__int.constructor_3 + prim__int.new + ^ + + [] > inc_post + prim__int.constructor_1 > old + prim__int.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__int.constructor_1 > old + prim__int.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__int.constructor_3 + prim__int.new + ^ + + [right] > add + seq > @ + prim__int.constructor_2 + prim__int.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__int.constructor_2 + prim__int.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__int.constructor_2 + prim__int.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__int.constructor_2 + prim__int.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__int.constructor_2 + prim__int.new + ^.v.mod + right.v + + seq > @ + this + + [right] > from + seq > @ + if. + or. + right.prim_name.eq "prim__float" + right.prim_name.eq "prim__double" + prim__int.constructor_2 + prim__int.new + right.v.as-int.mod + max_int + prim__int.constructor_2 + prim__int.new + right.v.mod + max_int + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prim__num.eo b/src/main/resources/stdlib/primitives/prim__num.eo new file mode 100644 index 00000000..f66246a7 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__num.eo @@ -0,0 +1,81 @@ ++package stdlib.primitives ++alias stdlib.primitives.prim__boolean + +[] > prim__num + [] > new + [] > this + "prim__num" > prim_name + "prim" > @ + memory > v + + [] > as-string + seq > @ + ^.v.as-string + + [this value] > init + seq > @ + this.v.write + value + + [right] > eq + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.eq + right.v + + [right] > greater + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.greater + right.v + + [right] > less + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.less + right.v + + [right] > geq + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.geq + right.v + + [right] > leq + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.leq + right.v + + [right] > neq + seq > @ + prim__boolean.constructor_2 + prim__boolean.new + ^.v.neq + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + this + + [this target] > constructor_2 + seq > @ + this.init + this + target + this + + [this another_num] > constructor_3 + seq > @ + this.init + this + another_num.v + this diff --git a/src/main/resources/stdlib/primitives/prim__short.eo b/src/main/resources/stdlib/primitives/prim__short.eo new file mode 100644 index 00000000..045cc6f4 --- /dev/null +++ b/src/main/resources/stdlib/primitives/prim__short.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__short + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__short" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__short.constructor_3 + prim__short.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__short.constructor_3 + prim__short.new + ^ + + [] > inc_post + prim__short.constructor_1 > old + prim__short.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__short.constructor_1 > old + prim__short.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__short.constructor_3 + prim__short.new + ^ + + [right] > add + seq > @ + prim__short.constructor_2 + prim__short.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__short.constructor_2 + prim__short.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__short.constructor_2 + prim__short.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__short.constructor_2 + prim__short.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__short.constructor_2 + prim__short.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/primitives/prin__long.eo b/src/main/resources/stdlib/primitives/prin__long.eo new file mode 100644 index 00000000..248b93ea --- /dev/null +++ b/src/main/resources/stdlib/primitives/prin__long.eo @@ -0,0 +1,116 @@ +# inc_pre, dec_pre, inc_post, dec_post, add, sub, mul, div are not precise operators ++package stdlib.primitives ++alias stdlib.primitives.prim__num + +[] > prim__long + prim__num > super + super > @ + + [] > new + [] > this + prim__num.new > super + super > @ + "prim__long" > prim_name + + [] > inc_pre + seq > @ + ^.v.write + ^.v.add + 1 + prim__long.constructor_3 + prim__long.new + ^ + + [] > dec_pre + seq > @ + ^.v.write + ^.v.sub + 1 + prim__long.constructor_3 + prim__long.new + ^ + + [] > inc_post + prim__long.constructor_1 > old + prim__long.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.add + 1 + old + + [] > dec_post + prim__long.constructor_1 > old + prim__long.new + seq > @ + old.v.write + ^.v + ^.v.write + ^.v.sub + 1 + old + + [right] > write + seq > @ + ^.v.write + right.v + prim__long.constructor_3 + prim__long.new + ^ + + [right] > add + seq > @ + prim__long.constructor_2 + prim__long.new + ^.v.add + right.v + + [right] > sub + seq > @ + prim__long.constructor_2 + prim__long.new + ^.v.sub + right.v + + [right] > mul + seq > @ + prim__long.constructor_2 + prim__long.new + ^.v.mul + right.v + + [right] > div + seq > @ + prim__long.constructor_2 + prim__long.new + ^.v.div + right.v + + [right] > mod + seq > @ + prim__long.constructor_2 + prim__long.new + ^.v.mod + right.v + + seq > @ + this + + [this] > constructor_1 + seq > @ + super.constructor_1 + this + + [this target] > constructor_2 + seq > @ + super.constructor_2 + this + target + + [this another_num] > constructor_3 + seq > @ + super.constructor_3 + this + another_num diff --git a/src/main/resources/stdlib/switch.eo b/src/main/resources/stdlib/switch.eo deleted file mode 100644 index db5de967..00000000 --- a/src/main/resources/stdlib/switch.eo +++ /dev/null @@ -1,4 +0,0 @@ -+package stdlib - -[c cases...] > switch - seq > @ diff --git a/src/test/resources/test_ready/SimpleTest.java b/src/test/resources/test_ready/SimpleTest.java index a78f2d60..7c519b8e 100644 --- a/src/test/resources/test_ready/SimpleTest.java +++ b/src/test/resources/test_ready/SimpleTest.java @@ -1,6 +1,8 @@ public class SimpleTest { public static void main(String[] args) { + int i = 0; + int j = i++; System.out.println("passed"); } } From e7d076565d0c941eaca52088d446fd934cb24cdc Mon Sep 17 00:00:00 2001 From: someilay Date: Thu, 28 Apr 2022 18:59:54 +0300 Subject: [PATCH 04/29] Hot fix --- src/test/resources/test_ready/SimpleTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/resources/test_ready/SimpleTest.java b/src/test/resources/test_ready/SimpleTest.java index 7c519b8e..a78f2d60 100644 --- a/src/test/resources/test_ready/SimpleTest.java +++ b/src/test/resources/test_ready/SimpleTest.java @@ -1,8 +1,6 @@ public class SimpleTest { public static void main(String[] args) { - int i = 0; - int j = i++; System.out.println("passed"); } } From 4867be9c9929201e601038bf0a35d3e96229fc43 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Mon, 2 May 2022 18:22:20 +0300 Subject: [PATCH 05/29] FEATURE: parsing method invocations Note There are significant differences between the way ANTLR parser produces the AST and out AST. So, adjustments should be done to produce correct AST for the j2eo translator. --- src/main/java/parser/TreeMappings.kt | 51 ++++++++++++++++--- .../java/tree/Expression/ArgumentList.java | 7 +++ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 604399f1..c64885b0 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -7,12 +7,11 @@ import parser.JavaParser.* import tree.* import tree.Compilation.* import tree.Declaration.* -import tree.Expression.Binary -import tree.Expression.Expression +import tree.Expression.* +import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.Literal +import tree.Expression.Primary.MethodInvocation import tree.Expression.Primary.This -import tree.Expression.SimpleReference -import tree.Expression.SwitchExpression import tree.Statement.* import tree.Type.* import kotlin.reflect.typeOf @@ -188,23 +187,61 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = MOD -> Token(TokenCode.Percent) XOR_ASSIGN -> Token(TokenCode.CaretAssign) LSHIFT_ASSIGN -> Token(TokenCode.LeftShiftAssign) + DOT -> Token(TokenCode.Dot) else -> throw Exception("unsupported token: $text ($type)") } fun CompoundName.toExpression() : Expression = SimpleReference(this) fun ExpressionContext.toExpression() : Expression = - primary()?.toExpression() ?: if (this.bop != null) { - if (expression(1) != null && expression(2) == null) { - Binary(expression(0).toExpression(), expression(1).toExpression(), bop.toToken()) + val expr0 = + expression(0)?.toExpression() ?: + primary()?.toExpression() + val expr1 = + expression(1)?.toExpression() ?: + primary()?.toExpression() ?: + methodCall()?.toExpression(expr0) ?: + SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + if (this.bop.text == ".") { + when (expr1) { + is MethodInvocation -> expr1 + // is SimpleReference -> FieldAccess( + // expr0, + // SUPER() != null, + // Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable + // ) + else -> SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + } } else { SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } + // if (expression(1) != null && expression(2) == null) { + // Binary(expression(0).toExpression(), expression(1).toExpression(), bop.toToken()) + // } else { + // SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + // } } else { + primary()?.toExpression() ?: + methodCall()?.toExpression(null) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } +fun MethodCallContext.toExpression(expr: Expression?) : Expression { + val args = ArgumentList( + expressionList().expression().stream().map { + it.toExpression() + }.toList() + ) + return MethodInvocation( + expr, + SUPER() != null, + null, // TODO: type arguments are somewhere else + identifier().toToken(), + args + ) +} + fun PrimaryContext.toExpression() : Expression? = expression()?.toExpression() ?: THIS()?.let { _ -> This(null) } ?: diff --git a/src/main/java/tree/Expression/ArgumentList.java b/src/main/java/tree/Expression/ArgumentList.java index 8c2cf442..b2868412 100644 --- a/src/main/java/tree/Expression/ArgumentList.java +++ b/src/main/java/tree/Expression/ArgumentList.java @@ -1,6 +1,8 @@ package tree.Expression; import java.util.ArrayList; +import java.util.Collection; + import tree.Entity; // Arguments @@ -25,6 +27,11 @@ public ArgumentList(Expression expr) { } } + public ArgumentList(Collection exprs) { + this.arguments = new ArrayList<>(); + this.arguments.addAll(exprs); + } + public ArgumentList add(Expression expr) { this.arguments.add(expr); if (expr != null) { From ab05142931118a77c9fc37b41d0913632e4ea347 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Wed, 4 May 2022 14:56:07 +0300 Subject: [PATCH 06/29] FEATURE: method invocations (wip) --- src/main/java/parser/TreeMappings.kt | 22 +++++++++++----- src/main/java/translator/MethodInvocations.kt | 26 +++++++++++++------ src/main/java/util/isSystemOutCall.kt | 18 ++++++------- 3 files changed, 42 insertions(+), 24 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index c64885b0..0aed7939 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -8,7 +8,7 @@ import tree.* import tree.Compilation.* import tree.Declaration.* import tree.Expression.* -import tree.Expression.Primary.FieldAccess +//import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.Literal import tree.Expression.Primary.MethodInvocation import tree.Expression.Primary.This @@ -197,20 +197,22 @@ fun ExpressionContext.toExpression() : Expression = if (this.bop != null) { val expr0 = expression(0)?.toExpression() ?: - primary()?.toExpression() + primary()?.toExpression() ?: + identifier()?.toExpression() val expr1 = expression(1)?.toExpression() ?: primary()?.toExpression() ?: + identifier()?.toExpression() ?: methodCall()?.toExpression(expr0) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ if (this.bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 - // is SimpleReference -> FieldAccess( - // expr0, - // SUPER() != null, - // Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable - // ) + is SimpleReference -> FieldAccess( + expr0, + SUPER() != null, + Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable + ) else -> SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } } else { @@ -222,7 +224,9 @@ fun ExpressionContext.toExpression() : Expression = // SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ // } } else { + expression(0)?.toExpression() ?: primary()?.toExpression() ?: + identifier()?.toExpression() ?: methodCall()?.toExpression(null) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } @@ -242,8 +246,12 @@ fun MethodCallContext.toExpression(expr: Expression?) : Expression { ) } +fun IdentifierContext.toExpression() : Expression = + SimpleReference(CompoundName(IDENTIFIER().text)) + fun PrimaryContext.toExpression() : Expression? = expression()?.toExpression() ?: + identifier()?.toExpression() ?: THIS()?.let { _ -> This(null) } ?: /* FIXME: super */ literal()?.toLiteral() ?: diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index f0370b97..9caddca3 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -7,11 +7,14 @@ import eotree.EODot import eotree.EOExpr import eotree.EOObject import eotree.eoDot +import tree.CompoundName import tree.Expression.Expression +import tree.Expression.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import util.ParseExprTasks import util.isSystemOutCall +import java.lang.reflect.Field // TODO: create state object to store binding of expression fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: MethodInvocation): EOObject { @@ -20,20 +23,27 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method val isStaticCall = !isSystemOutCall(methodInvocation) - val src: EODot = when (methodInvocation.qualifier) { - is SimpleReference -> - (methodInvocation.qualifier as SimpleReference).compoundName.eoDot() + val src: EODot = when (val methodQualifier = methodInvocation.qualifier) { + is SimpleReference -> methodQualifier.compoundName.eoDot() + is FieldAccess -> + when (val qualExpr = methodQualifier.expression) { + is SimpleReference -> CompoundName( + qualExpr.compoundName.names + listOf(methodQualifier.identifier) + ).eoDot() + else -> throw IllegalArgumentException("Unsupported yet") + } else -> - throw IllegalArgumentException("Only SimpleReference is supported") + throw IllegalArgumentException("Unsupported method qualifier!") } - val callee: EODot = when (methodInvocation.qualifier) { + val callee: EODot = when (val methodQualifier = methodInvocation.qualifier) { is SimpleReference -> - if ((methodInvocation.qualifier as SimpleReference).compoundName.names.size > 1) - (methodInvocation.qualifier as SimpleReference).compoundName.names.dropLast(1).eoDot() + if (methodQualifier.compoundName.names.size > 1) + methodQualifier.compoundName.names.dropLast(1).eoDot() else "this".eoDot() + is FieldAccess -> methodQualifier.identifier.eoDot() else -> - throw IllegalArgumentException("Only SimpleReference is supported") + throw IllegalArgumentException("Unsupported method qualifier!") } return EOObject( diff --git a/src/main/java/util/isSystemOutCall.kt b/src/main/java/util/isSystemOutCall.kt index d8f78e58..0b715bad 100644 --- a/src/main/java/util/isSystemOutCall.kt +++ b/src/main/java/util/isSystemOutCall.kt @@ -1,17 +1,17 @@ package util +import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference fun isSystemOutCall(methodInvocation: MethodInvocation): Boolean { - return if (methodInvocation.qualifier != null) { - if ((methodInvocation.qualifier as SimpleReference).compoundName.names.size == 3) { - (methodInvocation.qualifier as SimpleReference).compoundName.names[0] == "class__System" && - (methodInvocation.qualifier as SimpleReference).compoundName.names[1] == "out" - } else { - false + return methodInvocation.qualifier != null && + when (val methodQualifier = methodInvocation.qualifier) { + is SimpleReference -> + methodQualifier.compoundName.names.size == 3 + && methodQualifier.compoundName.names[0] == "class__System" + && methodQualifier.compoundName.names[1] == "out" + is FieldAccess -> false + else -> false } - } else { - false - } } From 5855f9ec6e6f7840d9cb841c8de44f2300bf792e Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Wed, 4 May 2022 15:02:23 +0300 Subject: [PATCH 07/29] FIX: string literal quotation marks --- src/main/java/parser/TreeMappings.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 0aed7939..48c6ee36 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -264,7 +264,7 @@ fun LiteralContext.toLiteral() : Literal? = integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text))} ?: NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } ?: floatLiteral()?.let { x -> Literal(Token(TokenCode.FloatingLiteral, x.text)) } ?: - STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text)) } ?: + STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text.drop(1).dropLast(1))) } ?: Literal(Token(TokenCode.IntegerLiteral, "123456")) ?: /* FIXME: support other literals */ throw Exception("unsupported literal $text") /* FIXME */ From 54fe33d4cdab7b662efded7469578c24556f6e35 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Wed, 4 May 2022 15:47:31 +0300 Subject: [PATCH 08/29] FEATURE: method invocations --- src/main/java/translator/MethodInvocations.kt | 4 ++-- src/main/java/translator/preprocessor/Preprocessor.kt | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index 9caddca3..1b35e710 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -24,11 +24,11 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method val isStaticCall = !isSystemOutCall(methodInvocation) val src: EODot = when (val methodQualifier = methodInvocation.qualifier) { - is SimpleReference -> methodQualifier.compoundName.eoDot() + is SimpleReference -> (methodQualifier.compoundName.names + listOf(methodInvocation.name)).eoDot() is FieldAccess -> when (val qualExpr = methodQualifier.expression) { is SimpleReference -> CompoundName( - qualExpr.compoundName.names + listOf(methodQualifier.identifier) + qualExpr.compoundName.names + listOf(methodQualifier.identifier, methodInvocation.name) ).eoDot() else -> throw IllegalArgumentException("Unsupported yet") } diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index d55db6ad..5e6136c1 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -7,6 +7,7 @@ import tree.Compilation.TopLevelComponent import tree.CompoundName import tree.Declaration.* import tree.Expression.Expression +import tree.Expression.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import tree.InitializerSimple @@ -224,6 +225,7 @@ private fun preprocessStmtExpr(state: PreprocessorState, stmExpr: StatementExpre private fun preprocessExpr(state: PreprocessorState, expr: Expression) { when (expr) { + is SimpleReference -> preprocessSimpleReference(state, expr) is MethodInvocation -> preprocessMethodInvocation(state, expr) else -> { // this is a generated else block @@ -232,8 +234,12 @@ private fun preprocessExpr(state: PreprocessorState, expr: Expression) { } private fun preprocessMethodInvocation(state: PreprocessorState, methodInvocation: MethodInvocation) { - when (methodInvocation.qualifier) { - is SimpleReference -> preprocessSimpleReference(state, methodInvocation.qualifier as SimpleReference) + when (val methodQualifier = methodInvocation.qualifier) { + is SimpleReference -> preprocessSimpleReference(state, methodQualifier) + is FieldAccess -> { + preprocessExpr(state, methodQualifier.expression) + preprocessCompoundName(state, CompoundName(methodQualifier.identifier)) + } else -> { // this is a generated else block } From 0cb31c99c9675d03ccc617032878b371f01350dc Mon Sep 17 00:00:00 2001 From: someilay Date: Thu, 5 May 2022 17:27:00 +0300 Subject: [PATCH 09/29] Blocks translation & code refactoring --- src/main/java/translator/Blocks.kt | 45 +++- src/main/java/translator/Declarations.kt | 94 ++++--- src/main/java/translator/Expressions.kt | 250 +++++++++++------- src/main/java/translator/Initializers.kt | 39 ++- src/main/java/translator/Literals.kt | 69 ++--- src/main/java/translator/MethodInvocations.kt | 33 ++- src/main/java/translator/Methods.kt | 89 +++---- src/main/java/translator/Statements.kt | 200 ++++++++++---- src/main/java/util/NewGenerator.kt | 3 +- src/main/java/util/StaticGenerator.kt | 3 +- 10 files changed, 541 insertions(+), 284 deletions(-) diff --git a/src/main/java/translator/Blocks.kt b/src/main/java/translator/Blocks.kt index bd4a99e6..696557d2 100644 --- a/src/main/java/translator/Blocks.kt +++ b/src/main/java/translator/Blocks.kt @@ -1,11 +1,52 @@ package translator import eotree.EOBndExpr +import eotree.EOCopy +import eotree.eoDot +import tree.Statement.Block +import tree.Statement.BlockStatement /** * In order to map Java block into EO, all variable declarations are separated out as memory objects and then seq * contains all the logic. */ -fun mapBlock(): EOBndExpr { - throw UnsupportedOperationException("Not implemented") +fun mapBlock(block: Block): List { + val parsedStatements = block.block.blockStatements + .associate { constructName(it) to mapBlockStatement(it, constructName(it)) } + + return listOf( + EOBndExpr( + EOCopy( + "seq", + parsedStatements.keys.map { it.eoDot() } + ), + "@" + ) + ) + parsedStatements.values.toList().flatten() +} + + +fun constructName(blockStatement: BlockStatement): String { + return if (blockStatement.statement != null) { + "s${blockStatement.hashCode()}" + } else if (blockStatement.expression != null) { + "e${blockStatement.hashCode()}" + } else if (blockStatement.declaration != null) { + "d${blockStatement.hashCode()}" + } else { + throw java.lang.IllegalArgumentException("Invalid block statement!") + } +} + + +fun mapBlockStatement(blockStatement: BlockStatement, name: String): List { + return if (blockStatement.statement != null) { + mapStatement(blockStatement.statement, name) + } else if (blockStatement.expression != null) { + mapExpression(blockStatement.expression, name) + } else if (blockStatement.declaration != null) { + mapDeclaration(blockStatement.declaration, name) + } else { + throw java.lang.IllegalArgumentException("Invalid block statement!") + } } diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index 1d70ed21..7dfe4ed1 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -3,11 +3,7 @@ package translator import arrow.core.None import arrow.core.Option import arrow.core.some -import eotree.EOBndExpr -import eotree.EOCopy -import eotree.EODot -import eotree.EOExpr -import eotree.eoDot +import eotree.* import lexer.TokenCode import tree.Declaration.ClassDeclaration import tree.Declaration.Declaration @@ -20,61 +16,91 @@ import tree.Type.TypeName import util.ParseExprTasks import util.TokenCodes -fun mapClassDeclaration(dec: Declaration): Option { +fun mapClassDeclaration(dec: Declaration): List { // TODO: get rid of option and implement all cases return when (dec) { is MethodDeclaration -> { - mapMethodDeclaration(dec).some() + listOf(mapMethodDeclaration(dec)) } is NormalClassDeclaration -> { - mapClass(dec as ClassDeclaration).some() + listOf(mapClass(dec as ClassDeclaration)) } is VariableDeclaration -> { - preMapVariableDeclaration(dec).some() + mapVariableDeclaration(dec, "n") } else -> { - None + listOf() } } } -/** - * Maps a variable declaration in class object (i.e. static variable). - */ -fun preMapVariableDeclaration(dec: VariableDeclaration): EOBndExpr = - when (dec.type) { - is TypeName -> - EOBndExpr(EODot("cage"), dec.name) - is PrimitiveType -> - EOBndExpr( - EOCopy( - listOf(decodePrimitiveType(dec.type as PrimitiveType).value, decodeInitializer(dec.initializer)).eoDot(), - listOf(decodePrimitiveType(dec.type as PrimitiveType).value, "new").eoDot() - ), - dec.name - ) - null -> - throw IllegalArgumentException("\"var\" declarations are not supported yet") - else -> - throw IllegalArgumentException("Type of type " + dec.type.javaClass.name + " is not supported") +fun mapDeclaration(dec: Declaration, name: String): List { + return when (dec) { + is MethodDeclaration -> { + listOf(mapMethodDeclaration(dec)) + } + is NormalClassDeclaration -> { + listOf(mapClass(dec as ClassDeclaration)) + } + is VariableDeclaration -> { + mapVariableDeclaration(dec, name) + } + else -> { + listOf() + } } +} -fun mapVariableDeclaration(parseExprTasks: ParseExprTasks, dec: VariableDeclaration): EOExpr = +fun mapVariableDeclaration(dec: VariableDeclaration, name: String): List = when (dec.type) { is TypeName -> { - EOCopy(listOf(dec.name, "write").eoDot(), parseExprTasks.addTask(dec.initializer).eoDot()) + listOf( + EOBndExpr( + EOCopy( + EODot("cage"), + ), + dec.name + ) + ) } is PrimitiveType -> { - EOCopy( - listOf(dec.name, "write").eoDot(), - parseExprTasks.addTask(dec.initializer).eoDot() + listOf( + EOBndExpr( + EOCopy( + listOf(decodePrimitiveType(dec.type as PrimitiveType).value, decodeInitializer(dec.initializer)).eoDot(), + listOf(decodePrimitiveType(dec.type as PrimitiveType).value, "new").eoDot() + ), + dec.name + ) ) } null -> throw IllegalArgumentException("\"var\" declarations are not supported yet") else -> throw IllegalArgumentException("Type of type " + dec.type.javaClass.name + " is not supported") + } + if (dec.initializer != null) { + listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(dec.name, "write").eoDot(), + constructInitName(dec.initializer).eoDot() + ), + "@" + ) + ) + ), + name + ) + ) + + mapInitializer(dec.initializer, constructInitName(dec.initializer)) + } else { + listOf() } fun decodePrimitiveType(type: PrimitiveType): TokenCodes { diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index dae0778e..f9e9349b 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -16,118 +16,175 @@ import tree.Expression.UnaryPostfix import tree.Expression.UnaryPrefix import util.ParseExprTasks -fun mapExpression(parseExprTasks: ParseExprTasks, expr: Expression): EOObject = +fun mapExpression(expr: Expression, name: String): List = when (expr) { is MethodInvocation -> - mapMethodInvocation(parseExprTasks, expr) + mapMethodInvocation(expr, name) is Literal -> - mapLiteral(expr) + listOf(mapLiteral(expr, name)) is UnaryPrefix -> - mapUnaryPrefix(parseExprTasks, expr) + mapUnaryPrefix(expr, name) is UnaryPostfix -> - mapUnaryPostfix(parseExprTasks, expr) + mapUnaryPostfix(expr, name) is Binary -> - mapBinary(parseExprTasks, expr) + mapBinary(expr, name) is SimpleReference -> - mapSimpleReference(parseExprTasks, expr) + listOf(mapSimpleReference(expr, name)) is FieldAccess -> - mapFieldAccess(parseExprTasks, expr) + mapFieldAccess(expr, name) is This -> - mapThis(expr) + listOf(mapThis(expr, name)) is Parenthesized -> - mapParenthesized(parseExprTasks, expr) + mapParenthesized(expr, name) else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } -fun mapParenthesized(parseExprTasks: ParseExprTasks, expr: Parenthesized): EOObject = - mapExpression(parseExprTasks, expr.expression) +fun constructExprName(expr: Expression): String = + when (expr) { + is MethodInvocation -> + "m_i${expr.hashCode()}" + is Literal -> + "l${expr.hashCode()}" + is UnaryPrefix -> + "u_pre${expr.hashCode()}" + is UnaryPostfix -> + "u_post${expr.hashCode()}" + is Binary -> + "b${expr.hashCode()}" + is SimpleReference -> + "s_r${expr.hashCode()}" + is FieldAccess -> + "f_a${expr.hashCode()}" + is This -> + "t${expr.hashCode()}" + is Parenthesized -> + "p${expr.hashCode()}" + else -> + throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") + } + +fun mapParenthesized(expr: Parenthesized, name: String): List = + listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + constructExprName(expr.expression) + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(expr.expression, constructExprName(expr.expression)) // TODO: add support for type -fun mapThis(expr: This): EOObject { - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - "this".eoDot() - ), - "@" +fun mapThis(expr: This, name: String): EOBndExpr { + return EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + "this" + ), + "@" + ) ) - ) + ), + name ) } -fun mapFieldAccess(parseExprTasks: ParseExprTasks, expr: FieldAccess): EOObject { - //"${mapExpression(expr.expression)}.${expr.identifier}".eoDot() - - val exprName = parseExprTasks.addTask(expr.expression) - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - listOf(exprName, expr.identifier).eoDot() - ), - "@" - ) +fun mapFieldAccess(expr: FieldAccess, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(expr.expression), expr.identifier).eoDot() + ), + "@" + ) + ) + ), + name ) - ) + ) + mapExpression(expr.expression, constructExprName(expr.expression)) } -fun mapUnaryPrefix(parseExprTasks: ParseExprTasks, expr: UnaryPrefix): EOObject { +fun mapUnaryPrefix(expr: UnaryPrefix, name: String): List { val function = when (expr.operator) { TokenCode.PlusPlus -> "inc_pre" TokenCode.MinusMinus -> "dec_pre" TokenCode.Minus -> "neg" TokenCode.Plus -> null - else -> throw IllegalArgumentException("Unary prefix ${expr.operator} is not supported") + else -> + "unary_placeholder" // FIXME } - val varName = parseExprTasks.addTask(expr.operand) - - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - if (function != null) { - listOf(varName, function).eoDot() - } else { - varName.eoDot() - }, - "@" - ) + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + if (function != null) { + listOf(constructExprName(expr.operand), function).eoDot() + } else { + constructExprName(expr.operand).eoDot() + } + ), + "@" + ) + ) + ), + name ) - ) + ) + mapExpression(expr.operand, constructExprName(expr.operand)) } -fun mapUnaryPostfix(parseExprTasks: ParseExprTasks, expr: UnaryPostfix): EOObject { +fun mapUnaryPostfix(expr: UnaryPostfix, name: String): List { val function = when (expr.operator) { TokenCode.PlusPlus -> "inc_post" TokenCode.MinusMinus -> "dec_post" - else -> throw IllegalArgumentException("Unary prefix ${expr.operator} is not supported") + else -> + "unary_placeholder" // FIXME } - val varName = parseExprTasks.addTask(expr.operand) - - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - listOf(varName, function).eoDot(), - "@" - ) + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(expr.operand), function).eoDot() + ), + "@" + ) + ) + ), + name ) - ) + ) + mapExpression(expr.operand, constructExprName(expr.operand)) } // TODO: add automatic casting for primitive types // TODO: populate with all Java binary operators -fun mapBinary(parseExprTasks: ParseExprTasks, expr: Binary): EOObject { +fun mapBinary(expr: Binary, name: String): List { val function = when (expr.operator) { TokenCode.Plus -> "add" TokenCode.Minus -> "sub" @@ -163,32 +220,39 @@ fun mapBinary(parseExprTasks: ParseExprTasks, expr: Binary): EOObject { // throw IllegalArgumentException("Binary operation ${expr.operator} is not supported") } - val leftName = parseExprTasks.addTask(expr.left) - val rightName = parseExprTasks.addTask(expr.right) - - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - listOf(leftName, function).eoDot(), - rightName.eoDot() - ), - "@" - ) + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(expr.left), function).eoDot(), + constructExprName(expr.right).eoDot() + ), + "@" + ) + ) + ), + name ) - ) + ) + mapExpression(expr.left, constructExprName(expr.left)) + mapExpression(expr.right, constructExprName(expr.right)) } -fun mapSimpleReference(parseExprTasks: ParseExprTasks, expr: SimpleReference): EOObject = - EOObject( - listOf(), - None, - listOf( - EOBndExpr( - expr.compoundName.eoDot(), - "@" +fun mapSimpleReference(expr: SimpleReference, name: String): EOBndExpr = + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + expr.compoundName.eoDot() + ), + "@" + ) ) - ) + ), + name ) diff --git a/src/main/java/translator/Initializers.kt b/src/main/java/translator/Initializers.kt index 27cc29e6..a10df030 100644 --- a/src/main/java/translator/Initializers.kt +++ b/src/main/java/translator/Initializers.kt @@ -1,21 +1,48 @@ package translator +import arrow.core.None +import eotree.EOBndExpr +import eotree.EOCopy import eotree.EOObject +import eotree.eoDot import tree.CompoundName import tree.Expression.SimpleReference import tree.Initializer import tree.InitializerSimple import util.ParseExprTasks -fun mapInitializer(parseExprTasks: ParseExprTasks, initializer: Initializer): EOObject { +fun mapInitializer(initializer: Initializer, name: String): List { return when (initializer) { - is InitializerSimple -> mapInitializerSimple(parseExprTasks, initializer) + is InitializerSimple -> mapInitializerSimple(initializer, name) else -> - mapInitializerSimple(parseExprTasks, InitializerSimple(SimpleReference(CompoundName("array_initializer_placeholder")))) // FIXME - // throw IllegalArgumentException("Initializer of type ${initializer.javaClass.simpleName} is not supported") + mapInitializerSimple(InitializerSimple(SimpleReference(CompoundName("array_initializer_placeholder"))), name) // FIXME } } -fun mapInitializerSimple(parseExprTasks: ParseExprTasks, initializerSimple: InitializerSimple): EOObject { - return mapExpression(parseExprTasks, initializerSimple.expression) +fun constructInitName(initializer: Initializer): String { + return when (initializer) { + is InitializerSimple -> "i_s${initializer.hashCode()}" + else -> + "un_i${initializer.hashCode()}" + } +} + +fun mapInitializerSimple(initializerSimple: InitializerSimple, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + constructExprName(initializerSimple.expression) + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(initializerSimple.expression, constructExprName(initializerSimple.expression)) } diff --git a/src/main/java/translator/Literals.kt b/src/main/java/translator/Literals.kt index 7d9c6dd3..85b251fc 100644 --- a/src/main/java/translator/Literals.kt +++ b/src/main/java/translator/Literals.kt @@ -9,53 +9,62 @@ import tree.Expression.Primary.Literal import tree.Type.PrimitiveType import util.TokenCodes -fun mapLiteral(literal: Literal): EOObject = +fun mapLiteral(literal: Literal, name: String): EOBndExpr = when (literal.code) { TokenCode.StringLiteral -> generateEOData( - listOf(TokenCodes.CLASS__STRING.value, "constructor_2").eoDot(), - listOf(TokenCodes.CLASS__STRING.value, "new").eoDot(), - EOStringData(literal.value as String) + listOf(TokenCodes.CLASS__STRING.value, "constructor_2").eoDot(), + listOf(TokenCodes.CLASS__STRING.value, "new").eoDot(), + EOStringData(literal.value as String), + name ) TokenCode.FloatingLiteral -> generateEOData( - listOf(TokenCodes.PRIM__FLOAT.value, "constructor_2").eoDot(), - listOf(TokenCodes.PRIM__FLOAT.value, "new").eoDot(), - EOFloatData((literal.value as String).toFloat()) + listOf(TokenCodes.PRIM__FLOAT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__FLOAT.value, "new").eoDot(), + EOFloatData((literal.value as String).toFloat()), + name ) TokenCode.IntegerLiteral -> generateEOData( - listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), - listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), - EOIntData(try {(literal.value as String).toInt()} catch (e: NumberFormatException) { 0 /* FIXME: parse integer literals */ }) + listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), + EOIntData(try {(literal.value as String).toInt()} catch (e: NumberFormatException) { 0 /* FIXME: parse integer literals */ }), + name ) TokenCode.True -> generateEOData( - listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), - listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), - EOBoolData(true) + listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), + EOBoolData(true), + name ) TokenCode.False -> generateEOData( - listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), - listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), - EOBoolData(false) + listOf(TokenCodes.PRIM__BOOLEAN.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__BOOLEAN.value, "new").eoDot(), + EOBoolData(false), + name ) TokenCode.Null -> generateEOData( /* FIXME: use proper null */ listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), - EOIntData(0) + EOIntData(0), + name ) else -> throw IllegalArgumentException("Mapping of type ${literal.javaClass.simpleName} (${literal.code}) is not supported.") } -fun generateEOData(primitiveTypeCall: EODot, primitiveNewCall: EODot, value: EOData) : EOObject = - EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - primitiveTypeCall, - primitiveNewCall, - value - ), - "@" +fun generateEOData(primitiveTypeCall: EODot, primitiveNewCall: EODot, value: EOData, name: String) : EOBndExpr = + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + primitiveTypeCall, + primitiveNewCall, + value + ), + "@" + ) ) - ) + ), + name ) diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index f0370b97..35829346 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -14,7 +14,7 @@ import util.ParseExprTasks import util.isSystemOutCall // TODO: create state object to store binding of expression -fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: MethodInvocation): EOObject { +fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List { require(!methodInvocation.superSign) { "Super sign isn't supported yet" } require(methodInvocation.typeArguments == null) { "Type arguments aren't supported yet" } @@ -36,18 +36,23 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method throw IllegalArgumentException("Only SimpleReference is supported") } - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - src, - (if (!isStaticCall) listOf(callee) else ArrayList()) + - (methodInvocation.arguments?.arguments?.map { obj -> parseExprTasks.addTask(obj).eoDot() } ?: listOf()) - ), - "@" - ) + return listOf( + EOBndExpr ( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + src, + (if (!isStaticCall) listOf(callee) else ArrayList()) + + (methodInvocation.arguments?.arguments?.map { obj -> constructExprName(obj).eoDot() } ?: listOf()) + ), + "@" + ) + ) + ), + name ) - ) + ) + (methodInvocation.arguments?.arguments?.map { mapExpression(it, constructExprName(it)) }?.flatten() ?: listOf()) } diff --git a/src/main/java/translator/Methods.kt b/src/main/java/translator/Methods.kt index a19c4ef8..49dde7e3 100644 --- a/src/main/java/translator/Methods.kt +++ b/src/main/java/translator/Methods.kt @@ -50,30 +50,9 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { None, // Bound attributes - // TODO: implement -// try { - if (dec.methodBody != null) ( - dec.methodBody.block.findAllLocalVariables().map { preMapVariableDeclaration(it) } + - listOf( - EOBndExpr( - EOCopy( - "seq", - dec.methodBody.block.blockStatements - .mapNotNull { - if (it.statement != null) - mapStatement(parseExprTasks, it.statement) - else if (it.expression != null) { - parseExprTasks.addTask(it.expression).eoDot() - } else if (it.declaration is VariableDeclaration && (it.declaration as VariableDeclaration).initializer != null) - mapVariableDeclaration(parseExprTasks, it.declaration as VariableDeclaration) - else - null - } - ), - "@" - ) - ) + parseExprTasks(parseExprTasks)) else -// } catch (e: NullPointerException) { + if (dec.methodBody != null) { + mapBlock(dec.methodBody) + } else { listOf( EOBndExpr( EOCopy( @@ -82,8 +61,8 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { ), "@" ) - ), -// }, + ) + }, "${dec.name} :: ${ dec.parameters?.parameters @@ -112,32 +91,32 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { ) } -fun parseExprTasks(parseExprTasks: ParseExprTasks): List { - return if (parseExprTasks.tasks.size > 0) { - parseExprTasks.tasks - .map { parseExprTask(it.second, it.first) } - .flatten() - } else { - listOf() - } -} - -fun parseExprTask(e: Entity, name: String): List { - val parseExprTasks = ParseExprTasks() - return when (e) { - is Expression -> { - listOf(EOBndExpr(mapExpression(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) - } - is Initializer -> { - listOf(EOBndExpr(mapInitializer(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) - } - else -> { - throw IllegalArgumentException("Entity of type ${e.javaClass.simpleName} cannot be parsed") - } - } -} - -fun BlockStatements.findAllLocalVariables(): List = - blockStatements - .filter { it.declaration is VariableDeclaration } - .map { it.declaration as VariableDeclaration } +//fun parseExprTasks(parseExprTasks: ParseExprTasks): List { +// return if (parseExprTasks.tasks.size > 0) { +// parseExprTasks.tasks +// .map { parseExprTask(it.second, it.first) } +// .flatten() +// } else { +// listOf() +// } +//} +// +//fun parseExprTask(e: Entity, name: String): List { +// val parseExprTasks = ParseExprTasks() +// return when (e) { +// is Expression -> { +// listOf(EOBndExpr(mapExpression(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) +// } +// is Initializer -> { +// listOf(EOBndExpr(mapInitializer(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) +// } +// else -> { +// throw IllegalArgumentException("Entity of type ${e.javaClass.simpleName} cannot be parsed") +// } +// } +//} +// +//fun BlockStatements.findAllLocalVariables(): List = +// blockStatements +// .filter { it.declaration is VariableDeclaration } +// .map { it.declaration as VariableDeclaration } diff --git a/src/main/java/translator/Statements.kt b/src/main/java/translator/Statements.kt index 158dab60..472cd740 100644 --- a/src/main/java/translator/Statements.kt +++ b/src/main/java/translator/Statements.kt @@ -1,12 +1,11 @@ package translator +import arrow.core.None import arrow.core.Option -import eotree.EOCopy -import eotree.EODot -import eotree.EOExpr -import eotree.eoDot +import eotree.* import tree.Statement.* import util.ParseExprTasks +import java.util.Random // fun mapBlockStatement(stmt: BlockStatement): EOExpr = // // Block statement is one of three variants @@ -21,68 +20,173 @@ import util.ParseExprTasks // throw IllegalArgumentException("BlockStatement does not have any known type") // } -fun mapStatement(parseExprTasks: ParseExprTasks, statement: Statement): EOExpr = +fun mapStatement(statement: Statement, name: String): List = when (statement) { - is StatementExpression -> mapStatementExpression(parseExprTasks, statement) - is Return -> mapReturnStatement(parseExprTasks, statement) - is IfThenElse -> mapIfThenElseStatement(parseExprTasks, statement) - is While -> mapWhileStatement(parseExprTasks, statement) - is Do -> mapDoStatement(parseExprTasks, statement) + is StatementExpression -> mapStatementExpression(statement, name) + is Return -> mapReturnStatement(statement, name) + is IfThenElse -> mapIfThenElseStatement(statement, name) + is While -> mapWhileStatement(statement, name) + is Do -> mapDoStatement(statement, name) // is Switch -> mapSwitchStatement(parseExprTasks, statement) else -> - "statement_placeholder".eoDot() // FIXME + listOf() // FIXME // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") } -fun mapStatementExpression(parseExprTasks: ParseExprTasks, stmtExpr: StatementExpression): EOExpr { - return parseExprTasks.addTask(stmtExpr.expression).eoDot() +fun mapEmptyStmt(name: String) : EOBndExpr = + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + "0".eoDot() + ), + "@" + ) + ) + ), + name + ) + +fun constructStmtName(statement: Statement): String = + when (statement) { + is StatementExpression -> "se${statement.hashCode()}" + is Return -> "r${statement.hashCode()}" + is IfThenElse -> "if_t_e${statement.hashCode()}" + is While -> "w${statement.hashCode()}" + is Do -> "do${statement.hashCode()}" + // is Switch -> mapSwitchStatement(parseExprTasks, statement) + else -> + "unknown${statement.hashCode()}" // FIXME + // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") + } + + +fun mapStatementExpression(stmtExpr: StatementExpression, name: String): List { + return mapExpression(stmtExpr.expression, name) } -fun mapReturnStatement(parseExprTasks: ParseExprTasks, rn: Return): EOExpr { - if (rn.expression != null) { - return parseExprTasks.addTask(rn.expression).eoDot() +fun mapReturnStatement(rn: Return, name: String): List { + return if (rn.expression != null) { + listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + constructExprName(rn.expression) + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(rn.expression, constructExprName(rn.expression)) } else { - return "return_placeholder".eoDot() + listOf() } } -fun mapIfThenElseStatement(parseExprTasks: ParseExprTasks, rn: IfThenElse): EOExpr = - if (rn.elsePart == null) { - EOCopy( - EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), - "if" +fun mapIfThenElseStatement(rn: IfThenElse, name: String): List { + val emptyName = "empty${Random().nextInt(Int.MAX_VALUE)}" + + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(rn.condition), "if").eoDot(), + constructStmtName(rn.thenPart).eoDot(), + if (rn.elsePart != null) { + constructStmtName(rn.elsePart).eoDot() + } else { + emptyName.eoDot() + } + ), + "@" + ) + ) ), - mapStatement(parseExprTasks, rn.thenPart) + name ) - } else { - EOCopy( - EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), - "if" + ) + mapExpression(rn.condition, constructExprName(rn.condition)) + + mapStatement(rn.thenPart, constructStmtName(rn.thenPart)) + + if (rn.elsePart != null) { + mapStatement(rn.elsePart,constructStmtName(rn.elsePart)) + } else { + listOf(mapEmptyStmt(emptyName)) + } +} + +fun mapWhileStatement(rn: While, name: String): List { + val emptyName = "empty${Random().nextInt(Int.MAX_VALUE)}" + + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(rn.condition), "while").eoDot(), + if (rn.statement != null) { + constructStmtName(rn.statement).eoDot() + } else { + emptyName.eoDot() + } + ), + "@" + ) + ) ), - mapStatement(parseExprTasks, rn.thenPart), - mapStatement(parseExprTasks, rn.elsePart) + name ) - } + ) + if (rn.statement != null) { + mapStatement(rn.statement,constructStmtName(rn.statement)) + } else { + listOf(mapEmptyStmt(emptyName)) + } +} -fun mapWhileStatement(parseExprTasks: ParseExprTasks, rn: While): EOExpr = - EOCopy( - EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), - "while" - ), - mapStatement(parseExprTasks, rn.statement) - ) +fun mapDoStatement(rn: Do, name: String): List { + val emptyName = "empty${Random().nextInt()}" -fun mapDoStatement(parseExprTasks: ParseExprTasks, rn: Do): EOExpr = - EOCopy( - EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), - "while" - ), - mapStatement(parseExprTasks, rn.statement) - ) + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(rn.condition), "do").eoDot(), + if (rn.statement != null) { + constructStmtName(rn.statement).eoDot() + } else { + emptyName.eoDot() + } + ), + "@" + ) + ) + ), + name + ) + ) + if (rn.statement != null) { + mapStatement(rn.statement,constructStmtName(rn.statement)) + } else { + listOf(mapEmptyStmt(emptyName)) + } +} // fun mapIfThenElse(statement: IfThenElse): EOExpr = // EOCopy( diff --git a/src/main/java/util/NewGenerator.kt b/src/main/java/util/NewGenerator.kt index 065793fc..38219240 100644 --- a/src/main/java/util/NewGenerator.kt +++ b/src/main/java/util/NewGenerator.kt @@ -1,6 +1,7 @@ package util import arrow.core.None +import arrow.core.flatten import arrow.core.flattenOption import eotree.EOBndExpr import eotree.EOCopy @@ -41,7 +42,7 @@ fun generateThis(clsDec: NormalClassDeclaration): EOBndExpr { dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } == null } .map { mapClassDeclaration(it) } - .flattenOption() + .flatten() else listOf() ), diff --git a/src/main/java/util/StaticGenerator.kt b/src/main/java/util/StaticGenerator.kt index d133cc42..97614623 100644 --- a/src/main/java/util/StaticGenerator.kt +++ b/src/main/java/util/StaticGenerator.kt @@ -1,5 +1,6 @@ package util +import arrow.core.flatten import arrow.core.flattenOption import eotree.EOBndExpr import lexer.TokenCode @@ -15,7 +16,7 @@ fun generateStatic(clsDec: NormalClassDeclaration): List { dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } != null } // TODO .map { mapClassDeclaration(it) } - .flattenOption() + .flatten() } catch (e: NullPointerException) { return ArrayList() } From 76f3b83b051c201735feea602fb553ee2bdd0191 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Thu, 5 May 2022 17:35:53 +0300 Subject: [PATCH 10/29] FIX: no argument invocations --- src/main/java/parser/TreeMappings.kt | 7 ++++--- src/main/java/translator/MethodInvocations.kt | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 48c6ee36..9268eadd 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -233,9 +233,10 @@ fun ExpressionContext.toExpression() : Expression = fun MethodCallContext.toExpression(expr: Expression?) : Expression { val args = ArgumentList( - expressionList().expression().stream().map { - it.toExpression() - }.toList() + if (expressionList() == null) + listOf() + else + expressionList().expression().stream().map { it.toExpression() }.toList() ) return MethodInvocation( expr, diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index 1b35e710..366502fe 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -32,6 +32,7 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method ).eoDot() else -> throw IllegalArgumentException("Unsupported yet") } + null -> methodInvocation.name.eoDot() else -> throw IllegalArgumentException("Unsupported method qualifier!") } @@ -42,6 +43,7 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method else "this".eoDot() is FieldAccess -> methodQualifier.identifier.eoDot() + null -> "this".eoDot() else -> throw IllegalArgumentException("Unsupported method qualifier!") } From 873eed6f94a3f53edbebbcf0fd1ce4f1d62ed29a Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Thu, 5 May 2022 19:29:13 +0300 Subject: [PATCH 11/29] Fixed if condition --- src/main/java/eotree/EODot.kt | 6 ++- src/main/java/eotree/EODotObject.kt | 50 +++++++++++++++++++++ src/main/java/eotree/EOObject.kt | 2 +- src/main/java/parser/TreeMappings.kt | 13 +++--- src/main/java/translator/Expressions.kt | 23 +++++----- src/main/java/translator/Methods.kt | 59 +++++++++++++------------ src/main/java/translator/Statements.kt | 7 +-- src/main/java/translator/Translator.kt | 4 +- src/main/java/util/ParseExprTasks.kt | 20 ++++++++- 9 files changed, 127 insertions(+), 57 deletions(-) create mode 100644 src/main/java/eotree/EODotObject.kt diff --git a/src/main/java/eotree/EODot.kt b/src/main/java/eotree/EODot.kt index 63226057..c7570b83 100644 --- a/src/main/java/eotree/EODot.kt +++ b/src/main/java/eotree/EODot.kt @@ -38,7 +38,11 @@ class EODot : EOExpr { override fun generateEO(indent: Int): String = src - .map { src -> src.generateEO(indent) + "." + name } + .map { src -> + val text = src.generateEO(indent).split("\n") + (listOf(text.first() + "." + name) + text.drop(1)) + .joinToString("\n") + } .getOrElse { indent(indent) + name } override fun toString(): String = diff --git a/src/main/java/eotree/EODotObject.kt b/src/main/java/eotree/EODotObject.kt new file mode 100644 index 00000000..c69aa39d --- /dev/null +++ b/src/main/java/eotree/EODotObject.kt @@ -0,0 +1,50 @@ +package eotree + +import arrow.core.* +import tree.CompoundName + +class EODotObject : EOObject { + var src: Option + var name: String + + constructor(name: String) : this(name.split(".")) + + constructor(names: List) : super(listOf(), None, listOf()) { + this.name = names.last() + this.src = if (names.size > 1) + EODot(names.dropLast(1)).some() + else + None + } + + constructor(src: Option, name: String) : super(listOf(), None, listOf()) { + this.src = src + this.name = name + } + + constructor(name: CompoundName) : super(listOf(), None, listOf()) { + // println("Mapping ${name.concatenatedJava()}") + // Recursively build a dot expression + this.src = + if (name.names.size >= 2) + Some(EODot(CompoundName(name.names.dropLast(1)))) + else None + this.name = name.names.last() + } + + override fun generateEO(indent: Int): String = + src + .map { src -> src.generateEO(indent) + "." + name } + .getOrElse { indent(indent) + name } + + override fun toString(): String = + src + .map { src -> "$src.$name" } + .getOrElse { name } +} + +fun String.eoDotObject(): EODotObject = EODotObject(this) + +fun CompoundName.eoDotObject(): EODotObject = EODotObject(this) + +fun List.eoDotObject(): EODotObject = EODotObject(this) diff --git a/src/main/java/eotree/EOObject.kt b/src/main/java/eotree/EOObject.kt index 617461ae..2b113c72 100644 --- a/src/main/java/eotree/EOObject.kt +++ b/src/main/java/eotree/EOObject.kt @@ -3,7 +3,7 @@ package eotree import arrow.core.Option import arrow.core.getOrElse -class EOObject( +open class EOObject( var freeAttrs: List, var varargAttr: Option, var bndAttrs: List, diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 48c6ee36..46d20dd6 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -8,13 +8,11 @@ import tree.* import tree.Compilation.* import tree.Declaration.* import tree.Expression.* -//import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.Literal import tree.Expression.Primary.MethodInvocation import tree.Expression.Primary.This import tree.Statement.* import tree.Type.* -import kotlin.reflect.typeOf fun CompilationUnitContext.toCompilationUnit() : CompilationUnit = SimpleCompilationUnit( @@ -204,7 +202,7 @@ fun ExpressionContext.toExpression() : Expression = primary()?.toExpression() ?: identifier()?.toExpression() ?: methodCall()?.toExpression(expr0) ?: - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + SimpleReference(CompoundName("expression_placeholder_expr1")) /* FIXME */ if (this.bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 @@ -213,10 +211,11 @@ fun ExpressionContext.toExpression() : Expression = SUPER() != null, Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable ) - else -> SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + else -> SimpleReference(CompoundName("expression_placeholder_bop_dot")) /* FIXME */ } } else { - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + Binary(expr0, expr1, bop.toToken()) +// SimpleReference(CompoundName("expression_placeholder_not_bop_dot")) /* FIXME */ } // if (expression(1) != null && expression(2) == null) { // Binary(expression(0).toExpression(), expression(1).toExpression(), bop.toToken()) @@ -228,12 +227,12 @@ fun ExpressionContext.toExpression() : Expression = primary()?.toExpression() ?: identifier()?.toExpression() ?: methodCall()?.toExpression(null) ?: - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + SimpleReference(CompoundName("expression_placeholder_not_bop")) /* FIXME */ } fun MethodCallContext.toExpression(expr: Expression?) : Expression { val args = ArgumentList( - expressionList().expression().stream().map { + expressionList().expression().map { it.toExpression() }.toList() ) diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index dae0778e..0cafaf42 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -160,25 +160,22 @@ fun mapBinary(parseExprTasks: ParseExprTasks, expr: Binary): EOObject { TokenCode.Caret -> "bit_xor" /* TODO: double check */ else -> "binary_op_placeholder" // FIXME - // throw IllegalArgumentException("Binary operation ${expr.operator} is not supported") + // throw IllegalArgumentException("Binary operation ${expr.operator} is not supported") } val leftName = parseExprTasks.addTask(expr.left) val rightName = parseExprTasks.addTask(expr.right) - - return EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - listOf(leftName, function).eoDot(), - rightName.eoDot() - ), - "@" - ) + val result = parseExprTasks.addReadyBinding( + EOBndExpr( + EOCopy( + listOf(leftName, function).eoDot(), + rightName.eoDot() + ), + "@" ) ) + + return result.eoDotObject() } fun mapSimpleReference(parseExprTasks: ParseExprTasks, expr: SimpleReference): EOObject = diff --git a/src/main/java/translator/Methods.kt b/src/main/java/translator/Methods.kt index a19c4ef8..5a4877c8 100644 --- a/src/main/java/translator/Methods.kt +++ b/src/main/java/translator/Methods.kt @@ -53,26 +53,30 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { // TODO: implement // try { if (dec.methodBody != null) ( - dec.methodBody.block.findAllLocalVariables().map { preMapVariableDeclaration(it) } + - listOf( - EOBndExpr( - EOCopy( - "seq", - dec.methodBody.block.blockStatements - .mapNotNull { - if (it.statement != null) - mapStatement(parseExprTasks, it.statement) - else if (it.expression != null) { - parseExprTasks.addTask(it.expression).eoDot() - } else if (it.declaration is VariableDeclaration && (it.declaration as VariableDeclaration).initializer != null) - mapVariableDeclaration(parseExprTasks, it.declaration as VariableDeclaration) - else - null - } - ), - "@" - ) - ) + parseExprTasks(parseExprTasks)) else + dec.methodBody.block.findAllLocalVariables().map { preMapVariableDeclaration(it) } + + listOf( + EOBndExpr( + EOCopy( + "seq", + dec.methodBody.block.blockStatements + .mapNotNull { + if (it.statement != null) + mapStatement(parseExprTasks, it.statement) + else if (it.expression != null) { + parseExprTasks.addTask(it.expression).eoDot() + } else if (it.declaration is VariableDeclaration && (it.declaration as VariableDeclaration).initializer != null) + mapVariableDeclaration( + parseExprTasks, + it.declaration as VariableDeclaration + ) + else + null + } + ), + "@" + ) + ) + parseExprTasks(parseExprTasks)) + else // } catch (e: NullPointerException) { listOf( EOBndExpr( @@ -112,15 +116,12 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { ) } -fun parseExprTasks(parseExprTasks: ParseExprTasks): List { - return if (parseExprTasks.tasks.size > 0) { - parseExprTasks.tasks - .map { parseExprTask(it.second, it.first) } - .flatten() - } else { - listOf() - } -} +fun parseExprTasks(parseExprTasks: ParseExprTasks): List = + parseExprTasks.tasks + .map { parseExprTask(it.second, it.first) } + .flatten() + + parseExprTasks.readyBindings.map { it.second } + fun parseExprTask(e: Entity, name: String): List { val parseExprTasks = ParseExprTasks() diff --git a/src/main/java/translator/Statements.kt b/src/main/java/translator/Statements.kt index 158dab60..4cc1340a 100644 --- a/src/main/java/translator/Statements.kt +++ b/src/main/java/translator/Statements.kt @@ -1,6 +1,7 @@ package translator import arrow.core.Option +import arrow.core.toOption import eotree.EOCopy import eotree.EODot import eotree.EOExpr @@ -30,7 +31,7 @@ fun mapStatement(parseExprTasks: ParseExprTasks, statement: Statement): EOExpr = is Do -> mapDoStatement(parseExprTasks, statement) // is Switch -> mapSwitchStatement(parseExprTasks, statement) else -> - "statement_placeholder".eoDot() // FIXME + "statement_placeholder_mapStatement".eoDot() // FIXME // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") } @@ -50,7 +51,7 @@ fun mapIfThenElseStatement(parseExprTasks: ParseExprTasks, rn: IfThenElse): EOEx if (rn.elsePart == null) { EOCopy( EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), + mapExpression(parseExprTasks, rn.condition).toOption(), "if" ), mapStatement(parseExprTasks, rn.thenPart) @@ -58,7 +59,7 @@ fun mapIfThenElseStatement(parseExprTasks: ParseExprTasks, rn: IfThenElse): EOEx } else { EOCopy( EODot( - Option.fromNullable(mapExpression(parseExprTasks, rn.condition)), + mapExpression(parseExprTasks, rn.condition).toOption(), "if" ), mapStatement(parseExprTasks, rn.thenPart), diff --git a/src/main/java/translator/Translator.kt b/src/main/java/translator/Translator.kt index fbb01434..d313ac6c 100644 --- a/src/main/java/translator/Translator.kt +++ b/src/main/java/translator/Translator.kt @@ -61,9 +61,9 @@ class Translator { // FIXME: assuming there is only one top-level component and it is a class // Always calling the 'main' method - val stdAliases = preprocessorState.stdTokensForCurrentAlias.stream() + val stdAliases = preprocessorState.stdTokensForCurrentAlias .map { EOMeta("alias", it) }.toList() - val eoAliases = preprocessorState.eoClassesForCurrentAlias.stream() + val eoAliases = preprocessorState.eoClassesForCurrentAlias .map { EOMeta("alias", it) }.toList() return EOProgram( diff --git a/src/main/java/util/ParseExprTasks.kt b/src/main/java/util/ParseExprTasks.kt index b4ce967b..c26798b1 100644 --- a/src/main/java/util/ParseExprTasks.kt +++ b/src/main/java/util/ParseExprTasks.kt @@ -1,15 +1,33 @@ package util -import eotree.EOExpr +import arrow.core.None +import eotree.EOBndExpr +import eotree.EOObject import tree.Entity import kotlin.collections.ArrayList class ParseExprTasks { val tasks = ArrayList>() + val readyBindings = mutableListOf>() fun addTask(e: Entity): String { val name = "e_${e.hashCode()}" tasks.add(Pair(name, e)) return name } + + fun addReadyBinding(obj: EOBndExpr): String { + val name = "e_${obj.hashCode()}" + + val newObj = EOBndExpr( + EOObject( + listOf(), + None, + listOf(obj) + ), + name + ) + readyBindings.add(Pair(name, newObj)) + return name + } } \ No newline at end of file From 056c0179f5b543fa1120ce075d0ce599089b6130 Mon Sep 17 00:00:00 2001 From: someilay Date: Thu, 5 May 2022 20:23:45 +0300 Subject: [PATCH 12/29] Hotfix --- src/main/java/parser/JavaParser.java | 12 ++++++ src/main/java/parser/TreeMappings.kt | 58 +++++++++++++++++++++++--- src/main/java/translator/Blocks.kt | 22 +++++++++- src/main/java/translator/Statements.kt | 56 +++++++++++++++++-------- 4 files changed, 123 insertions(+), 25 deletions(-) diff --git a/src/main/java/parser/JavaParser.java b/src/main/java/parser/JavaParser.java index 37496265..492a1831 100644 --- a/src/main/java/parser/JavaParser.java +++ b/src/main/java/parser/JavaParser.java @@ -9078,6 +9078,18 @@ public List annotation() { public AnnotationContext annotation(int i) { return getRuleContext(AnnotationContext.class,i); } + public TerminalNode terminal(int i) { + int j = -1; + for (ParseTree o : children) { + if ( o instanceof TerminalNode ) { + j++; + if ( j == i ) { + return (TerminalNode)o; + } + } + } + return null; + } public List BITAND() { return getTokens(JavaParser.BITAND); } public TerminalNode BITAND(int i) { return getToken(JavaParser.BITAND, i); diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 48c6ee36..7f3f5394 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -11,6 +11,7 @@ import tree.Expression.* //import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.Literal import tree.Expression.Primary.MethodInvocation +import tree.Expression.Primary.Parenthesized import tree.Expression.Primary.This import tree.Statement.* import tree.Type.* @@ -120,7 +121,7 @@ fun StatementContext.toStatement() : Statement = is StatementBreakContext -> Break(null, identifier()?.toToken()) is StatementContinueContext -> Continue(null, identifier()?.toToken()) is StatementForContext -> StatementExpression(null, SimpleReference(CompoundName("for_loop_placeholder"))) /* FIXME */ - is StatementBlockLabelContext -> StatementExpression(null, SimpleReference(CompoundName("block_label_placeholder"))) /* FIXME */ + is StatementBlockLabelContext -> block().toBlock() is StatementDoContext -> Do(null, statement().toStatement(), parExpression().expression().toExpression()) is StatementReturnContext -> Return(null, expression()?.toExpression()) is StatementIdentifierLabelContext -> StatementExpression(null, SimpleReference(CompoundName("identifier_label_placeholder"))) /* FIXME */ @@ -188,13 +189,41 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = XOR_ASSIGN -> Token(TokenCode.CaretAssign) LSHIFT_ASSIGN -> Token(TokenCode.LeftShiftAssign) DOT -> Token(TokenCode.Dot) + INC -> Token(TokenCode.PlusPlus) + DEC -> Token(TokenCode.MinusMinus) else -> throw Exception("unsupported token: $text ($type)") } fun CompoundName.toExpression() : Expression = SimpleReference(this) +fun ExpressionContext.toBinaryExpression() : Binary? { + val expr0 = expression(0)?.toExpression() + val expr1 = expression(1)?.toExpression() + val operand = terminal(0)?.symbol + return if (expr0 != null && expr1 != null && operand != null) + Binary(expr0, expr1, operand.toToken()) + else + null +} + +fun ExpressionContext.toUnaryPrefixPostfix() : Expression? { + val expr = expression(0)?.toExpression() + val operand = terminal(0)?.symbol + return if (expr != null && operand != null) { + if (prefix != null) { + UnaryPrefix(operand.toToken(), expr) + } else if (postfix != null) { + UnaryPostfix(operand.toToken(), expr) + } else { + null + } + } else { + null + } +} + fun ExpressionContext.toExpression() : Expression = - if (this.bop != null) { + if (bop != null) { val expr0 = expression(0)?.toExpression() ?: primary()?.toExpression() ?: @@ -205,16 +234,19 @@ fun ExpressionContext.toExpression() : Expression = identifier()?.toExpression() ?: methodCall()?.toExpression(expr0) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ - if (this.bop.text == ".") { + if (bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 is SimpleReference -> FieldAccess( - expr0, - SUPER() != null, - Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable + expr0, + SUPER() != null, + Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable ) else -> SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } + } else if (bop.type in DOT..URSHIFT_ASSIGN) { + this.toBinaryExpression() ?: + SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } else { SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } @@ -224,6 +256,7 @@ fun ExpressionContext.toExpression() : Expression = // SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ // } } else { + this.toUnaryPrefixPostfix() ?: expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() ?: @@ -249,7 +282,20 @@ fun MethodCallContext.toExpression(expr: Expression?) : Expression { fun IdentifierContext.toExpression() : Expression = SimpleReference(CompoundName(IDENTIFIER().text)) +fun PrimaryContext.toParenthesized(): Parenthesized? = + if (LPAREN() != null && RPAREN() != null) { + val expr = expression()?.toExpression() + if (expr != null) { + Parenthesized(expr) + } else { + null + } + } else { + null + } + fun PrimaryContext.toExpression() : Expression? = + this.toParenthesized() ?: expression()?.toExpression() ?: identifier()?.toExpression() ?: THIS()?.let { _ -> This(null) } ?: diff --git a/src/main/java/translator/Blocks.kt b/src/main/java/translator/Blocks.kt index 696557d2..b62aa2f9 100644 --- a/src/main/java/translator/Blocks.kt +++ b/src/main/java/translator/Blocks.kt @@ -1,7 +1,9 @@ package translator +import arrow.core.None import eotree.EOBndExpr import eotree.EOCopy +import eotree.EOObject import eotree.eoDot import tree.Statement.Block import tree.Statement.BlockStatement @@ -10,7 +12,20 @@ import tree.Statement.BlockStatement * In order to map Java block into EO, all variable declarations are separated out as memory objects and then seq * contains all the logic. */ -fun mapBlock(block: Block): List { +fun mapBlock(block: Block, name: String? = null): List { + if (name != null) { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + mapBlock(block) + ), + name + ) + ) + } + val parsedStatements = block.block.blockStatements .associate { constructName(it) to mapBlockStatement(it, constructName(it)) } @@ -18,7 +33,10 @@ fun mapBlock(block: Block): List { EOBndExpr( EOCopy( "seq", - parsedStatements.keys.map { it.eoDot() } + if (parsedStatements.isNotEmpty()) + parsedStatements.keys.map { it.eoDot() } + else + listOf("0".eoDot()) ), "@" ) diff --git a/src/main/java/translator/Statements.kt b/src/main/java/translator/Statements.kt index 472cd740..05a12750 100644 --- a/src/main/java/translator/Statements.kt +++ b/src/main/java/translator/Statements.kt @@ -27,6 +27,7 @@ fun mapStatement(statement: Statement, name: String): List = is IfThenElse -> mapIfThenElseStatement(statement, name) is While -> mapWhileStatement(statement, name) is Do -> mapDoStatement(statement, name) + is Block -> mapBlock(statement, name) // is Switch -> mapSwitchStatement(parseExprTasks, statement) else -> listOf() // FIXME @@ -57,6 +58,7 @@ fun constructStmtName(statement: Statement): String = is IfThenElse -> "if_t_e${statement.hashCode()}" is While -> "w${statement.hashCode()}" is Do -> "do${statement.hashCode()}" + is Block -> "b${statement.hashCode()}" // is Switch -> mapSwitchStatement(parseExprTasks, statement) else -> "unknown${statement.hashCode()}" // FIXME @@ -120,7 +122,7 @@ fun mapIfThenElseStatement(rn: IfThenElse, name: String): List { ) + mapExpression(rn.condition, constructExprName(rn.condition)) + mapStatement(rn.thenPart, constructStmtName(rn.thenPart)) + if (rn.elsePart != null) { - mapStatement(rn.elsePart,constructStmtName(rn.elsePart)) + mapStatement(rn.elsePart, constructStmtName(rn.elsePart)) } else { listOf(mapEmptyStmt(emptyName)) } @@ -138,11 +140,20 @@ fun mapWhileStatement(rn: While, name: String): List { EOBndExpr( EOCopy( listOf(constructExprName(rn.condition), "while").eoDot(), - if (rn.statement != null) { - constructStmtName(rn.statement).eoDot() - } else { - emptyName.eoDot() - } + EOObject( + listOf("while_i"), + None, + listOf( + EOBndExpr( + if (rn.statement != null) { + constructStmtName(rn.statement).eoDot() + } else { + emptyName.eoDot() + }, + "@" + ) + ) + ) ), "@" ) @@ -150,11 +161,12 @@ fun mapWhileStatement(rn: While, name: String): List { ), name ) - ) + if (rn.statement != null) { - mapStatement(rn.statement,constructStmtName(rn.statement)) - } else { - listOf(mapEmptyStmt(emptyName)) - } + ) + mapExpression(rn.condition, constructExprName(rn.condition)) + + if (rn.statement != null) { + mapStatement(rn.statement, constructStmtName(rn.statement)) + } else { + listOf(mapEmptyStmt(emptyName)) + } } fun mapDoStatement(rn: Do, name: String): List { @@ -169,11 +181,20 @@ fun mapDoStatement(rn: Do, name: String): List { EOBndExpr( EOCopy( listOf(constructExprName(rn.condition), "do").eoDot(), - if (rn.statement != null) { - constructStmtName(rn.statement).eoDot() - } else { - emptyName.eoDot() - } + EOObject( + listOf("do_i"), + None, + listOf( + EOBndExpr( + if (rn.statement != null) { + constructStmtName(rn.statement).eoDot() + } else { + emptyName.eoDot() + }, + "@" + ) + ) + ) ), "@" ) @@ -181,7 +202,8 @@ fun mapDoStatement(rn: Do, name: String): List { ), name ) - ) + if (rn.statement != null) { + ) + mapExpression(rn.condition, constructExprName(rn.condition)) + + if (rn.statement != null) { mapStatement(rn.statement,constructStmtName(rn.statement)) } else { listOf(mapEmptyStmt(emptyName)) From 0c934ab89b03ef97d0023a5fd7375f37ccde8bc4 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Fri, 6 May 2022 21:34:33 +0300 Subject: [PATCH 13/29] FEATURE: old tree removed Problem There were overlapping cases of old AST and the new one. Solution Remove old AST from the code. Note A foundation for instance creation translation created. --- src/main/java/parser/TreeMappings.kt | 209 ++++++++++++------ src/main/java/translator/Expressions.kt | 7 +- src/main/java/translator/MethodInvocations.kt | 4 +- .../translator/preprocessor/Preprocessor.kt | 2 +- src/main/java/tree/AnnoElementValue.java | 4 - src/main/java/tree/AnnoParameterList.java | 21 -- src/main/java/tree/Annotation.java | 46 ---- src/main/java/tree/Annotations.java | 33 --- .../tree/Compilation/CompilationUnit.java | 12 - src/main/java/tree/Compilation/Module.java | 5 - src/main/java/tree/Compilation/Package.java | 44 ---- .../Compilation/SimpleCompilationUnit.java | 39 ---- .../tree/Compilation/TopLevelComponent.java | 53 ----- .../tree/Compilation/TopLevelComponents.java | 47 ---- src/main/java/tree/CompoundName.java | 51 ----- .../java/tree/Declaration/CatchParameter.java | 44 ---- .../tree/Declaration/ClassDeclaration.java | 21 -- .../tree/Declaration/ClassInitializer.java | 32 --- .../tree/Declaration/ConstructorBody.java | 35 --- .../Declaration/ConstructorDeclaration.java | 55 ----- .../Declaration/ConstructorDeclarator.java | 34 --- .../java/tree/Declaration/Declaration.java | 72 ------ .../java/tree/Declaration/Declarations.java | 54 ----- src/main/java/tree/Declaration/EnumBody.java | 33 --- .../tree/Declaration/EnumDeclaration.java | 78 ------- .../java/tree/Declaration/Enumerator.java | 49 ---- .../java/tree/Declaration/Enumerators.java | 43 ---- .../ExplicitConstructorInvocation.java | 49 ---- .../tree/Declaration/ImportDeclaration.java | 46 ---- .../tree/Declaration/ImportDeclarations.java | 47 ---- .../Declaration/InterfaceDeclaration.java | 17 -- .../tree/Declaration/MethodDeclaration.java | 131 ----------- .../tree/Declaration/MethodDeclarator.java | 37 ---- .../java/tree/Declaration/MethodHeader.java | 53 ----- .../Declaration/NormalClassDeclaration.java | 126 ----------- .../NormalInterfaceDeclaration.java | 55 ----- .../Declaration/ParameterDeclaration.java | 88 -------- .../Declaration/ParameterDeclarations.java | 41 ---- .../java/tree/Declaration/ParameterTail.java | 45 ---- .../tree/Declaration/ReceiverDeclaration.java | 47 ---- .../tree/Declaration/RecordComponent.java | 45 ---- .../tree/Declaration/RecordComponents.java | 32 --- .../tree/Declaration/RecordDeclaration.java | 77 ------- .../tree/Declaration/TypeAndDeclarators.java | 28 --- .../tree/Declaration/VariableDeclaration.java | 80 ------- .../tree/Declaration/VariableDeclarator.java | 45 ---- .../tree/Declaration/VariableDeclarators.java | 42 ---- src/main/java/tree/Dim.java | 25 --- src/main/java/tree/Dims.java | 48 ---- src/main/java/tree/Entity.java | 66 ------ .../java/tree/Expression/ArgumentList.java | 51 ----- .../java/tree/Expression/ArrayAccess.java | 35 --- src/main/java/tree/Expression/Binary.java | 35 --- src/main/java/tree/Expression/Cast.java | 37 ---- .../java/tree/Expression/Conditional.java | 46 ---- src/main/java/tree/Expression/Expression.java | 6 - .../java/tree/Expression/Expressions.java | 35 --- .../java/tree/Expression/FieldAccess.java | 42 ---- src/main/java/tree/Expression/InstanceOf.java | 57 ----- src/main/java/tree/Expression/Lambda.java | 72 ------ .../tree/Expression/Primary/ClassLiteral.java | 38 ---- .../Expression/Primary/InstanceCreation.java | 28 --- .../java/tree/Expression/Primary/Literal.java | 38 ---- .../Expression/Primary/MethodInvocation.java | 85 ------- .../Expression/Primary/Parenthesized.java | 26 --- .../java/tree/Expression/Primary/Primary.java | 20 -- .../java/tree/Expression/Primary/This.java | 32 --- .../java/tree/Expression/SimpleReference.java | 26 --- .../tree/Expression/SwitchExpression.java | 31 --- .../java/tree/Expression/UnaryPostfix.java | 28 --- .../java/tree/Expression/UnaryPrefix.java | 28 --- src/main/java/tree/Initializer.java | 32 --- src/main/java/tree/InitializerArray.java | 38 ---- src/main/java/tree/InitializerSimple.java | 22 -- src/main/java/tree/Modifiers.java | 35 --- src/main/java/tree/ResourceSpecification.java | 18 -- src/main/java/tree/StandardModifiers.java | 53 ----- src/main/java/tree/Statement/Assert.java | 46 ---- src/main/java/tree/Statement/Block.java | 42 ---- .../java/tree/Statement/BlockStatement.java | 65 ------ .../java/tree/Statement/BlockStatements.java | 60 ----- src/main/java/tree/Statement/Break.java | 35 --- src/main/java/tree/Statement/CatchClause.java | 32 --- .../java/tree/Statement/CatchClauses.java | 41 ---- src/main/java/tree/Statement/Continue.java | 35 --- src/main/java/tree/Statement/Do.java | 36 --- src/main/java/tree/Statement/IfThenElse.java | 63 ------ src/main/java/tree/Statement/Return.java | 39 ---- src/main/java/tree/Statement/Statement.java | 86 ------- .../tree/Statement/StatementExpression.java | 35 --- .../tree/Statement/StatementExpressions.java | 27 --- src/main/java/tree/Statement/Switch.java | 96 -------- src/main/java/tree/Statement/SwitchBlock.java | 26 --- .../java/tree/Statement/SwitchBlocks.java | 39 ---- src/main/java/tree/Statement/SwitchLabel.java | 33 --- .../java/tree/Statement/SwitchLabels.java | 32 --- src/main/java/tree/Statement/SwitchRule.java | 87 -------- src/main/java/tree/Statement/SwitchRules.java | 32 --- .../java/tree/Statement/Synchronized.java | 36 --- src/main/java/tree/Statement/Throw.java | 36 --- src/main/java/tree/Statement/Try.java | 57 ----- src/main/java/tree/Statement/While.java | 39 ---- src/main/java/tree/Statement/Yield.java | 36 --- src/main/java/tree/Type/PrimitiveType.java | 44 ---- src/main/java/tree/Type/Type.java | 40 ---- src/main/java/tree/Type/TypeArgument.java | 51 ----- src/main/java/tree/Type/TypeArguments.java | 55 ----- src/main/java/tree/Type/TypeList.java | 51 ----- src/main/java/tree/Type/TypeName.java | 58 ----- src/main/java/tree/Type/TypeParameter.java | 49 ---- .../java/tree/Type/TypeParameterTail.java | 47 ---- src/main/java/tree/Type/TypeParameters.java | 45 ---- src/main/java/tree/Type/UnannotatedType.java | 37 ---- 113 files changed, 142 insertions(+), 4917 deletions(-) delete mode 100644 src/main/java/tree/AnnoElementValue.java delete mode 100644 src/main/java/tree/AnnoParameterList.java delete mode 100644 src/main/java/tree/Annotation.java delete mode 100644 src/main/java/tree/Annotations.java delete mode 100644 src/main/java/tree/Compilation/CompilationUnit.java delete mode 100644 src/main/java/tree/Compilation/Module.java delete mode 100644 src/main/java/tree/Compilation/Package.java delete mode 100644 src/main/java/tree/Compilation/SimpleCompilationUnit.java delete mode 100644 src/main/java/tree/Compilation/TopLevelComponent.java delete mode 100644 src/main/java/tree/Compilation/TopLevelComponents.java delete mode 100644 src/main/java/tree/CompoundName.java delete mode 100644 src/main/java/tree/Declaration/CatchParameter.java delete mode 100644 src/main/java/tree/Declaration/ClassDeclaration.java delete mode 100644 src/main/java/tree/Declaration/ClassInitializer.java delete mode 100644 src/main/java/tree/Declaration/ConstructorBody.java delete mode 100644 src/main/java/tree/Declaration/ConstructorDeclaration.java delete mode 100644 src/main/java/tree/Declaration/ConstructorDeclarator.java delete mode 100644 src/main/java/tree/Declaration/Declaration.java delete mode 100644 src/main/java/tree/Declaration/Declarations.java delete mode 100644 src/main/java/tree/Declaration/EnumBody.java delete mode 100644 src/main/java/tree/Declaration/EnumDeclaration.java delete mode 100644 src/main/java/tree/Declaration/Enumerator.java delete mode 100644 src/main/java/tree/Declaration/Enumerators.java delete mode 100644 src/main/java/tree/Declaration/ExplicitConstructorInvocation.java delete mode 100644 src/main/java/tree/Declaration/ImportDeclaration.java delete mode 100644 src/main/java/tree/Declaration/ImportDeclarations.java delete mode 100644 src/main/java/tree/Declaration/InterfaceDeclaration.java delete mode 100644 src/main/java/tree/Declaration/MethodDeclaration.java delete mode 100644 src/main/java/tree/Declaration/MethodDeclarator.java delete mode 100644 src/main/java/tree/Declaration/MethodHeader.java delete mode 100644 src/main/java/tree/Declaration/NormalClassDeclaration.java delete mode 100644 src/main/java/tree/Declaration/NormalInterfaceDeclaration.java delete mode 100644 src/main/java/tree/Declaration/ParameterDeclaration.java delete mode 100644 src/main/java/tree/Declaration/ParameterDeclarations.java delete mode 100644 src/main/java/tree/Declaration/ParameterTail.java delete mode 100644 src/main/java/tree/Declaration/ReceiverDeclaration.java delete mode 100644 src/main/java/tree/Declaration/RecordComponent.java delete mode 100644 src/main/java/tree/Declaration/RecordComponents.java delete mode 100644 src/main/java/tree/Declaration/RecordDeclaration.java delete mode 100644 src/main/java/tree/Declaration/TypeAndDeclarators.java delete mode 100644 src/main/java/tree/Declaration/VariableDeclaration.java delete mode 100644 src/main/java/tree/Declaration/VariableDeclarator.java delete mode 100644 src/main/java/tree/Declaration/VariableDeclarators.java delete mode 100644 src/main/java/tree/Dim.java delete mode 100644 src/main/java/tree/Dims.java delete mode 100644 src/main/java/tree/Entity.java delete mode 100644 src/main/java/tree/Expression/ArgumentList.java delete mode 100644 src/main/java/tree/Expression/ArrayAccess.java delete mode 100644 src/main/java/tree/Expression/Binary.java delete mode 100644 src/main/java/tree/Expression/Cast.java delete mode 100644 src/main/java/tree/Expression/Conditional.java delete mode 100644 src/main/java/tree/Expression/Expression.java delete mode 100644 src/main/java/tree/Expression/Expressions.java delete mode 100644 src/main/java/tree/Expression/FieldAccess.java delete mode 100644 src/main/java/tree/Expression/InstanceOf.java delete mode 100644 src/main/java/tree/Expression/Lambda.java delete mode 100644 src/main/java/tree/Expression/Primary/ClassLiteral.java delete mode 100644 src/main/java/tree/Expression/Primary/InstanceCreation.java delete mode 100644 src/main/java/tree/Expression/Primary/Literal.java delete mode 100644 src/main/java/tree/Expression/Primary/MethodInvocation.java delete mode 100644 src/main/java/tree/Expression/Primary/Parenthesized.java delete mode 100644 src/main/java/tree/Expression/Primary/Primary.java delete mode 100644 src/main/java/tree/Expression/Primary/This.java delete mode 100644 src/main/java/tree/Expression/SimpleReference.java delete mode 100644 src/main/java/tree/Expression/SwitchExpression.java delete mode 100644 src/main/java/tree/Expression/UnaryPostfix.java delete mode 100644 src/main/java/tree/Expression/UnaryPrefix.java delete mode 100644 src/main/java/tree/Initializer.java delete mode 100644 src/main/java/tree/InitializerArray.java delete mode 100644 src/main/java/tree/InitializerSimple.java delete mode 100644 src/main/java/tree/Modifiers.java delete mode 100644 src/main/java/tree/ResourceSpecification.java delete mode 100644 src/main/java/tree/StandardModifiers.java delete mode 100644 src/main/java/tree/Statement/Assert.java delete mode 100644 src/main/java/tree/Statement/Block.java delete mode 100644 src/main/java/tree/Statement/BlockStatement.java delete mode 100644 src/main/java/tree/Statement/BlockStatements.java delete mode 100644 src/main/java/tree/Statement/Break.java delete mode 100644 src/main/java/tree/Statement/CatchClause.java delete mode 100644 src/main/java/tree/Statement/CatchClauses.java delete mode 100644 src/main/java/tree/Statement/Continue.java delete mode 100644 src/main/java/tree/Statement/Do.java delete mode 100644 src/main/java/tree/Statement/IfThenElse.java delete mode 100644 src/main/java/tree/Statement/Return.java delete mode 100644 src/main/java/tree/Statement/Statement.java delete mode 100644 src/main/java/tree/Statement/StatementExpression.java delete mode 100644 src/main/java/tree/Statement/StatementExpressions.java delete mode 100644 src/main/java/tree/Statement/Switch.java delete mode 100644 src/main/java/tree/Statement/SwitchBlock.java delete mode 100644 src/main/java/tree/Statement/SwitchBlocks.java delete mode 100644 src/main/java/tree/Statement/SwitchLabel.java delete mode 100644 src/main/java/tree/Statement/SwitchLabels.java delete mode 100644 src/main/java/tree/Statement/SwitchRule.java delete mode 100644 src/main/java/tree/Statement/SwitchRules.java delete mode 100644 src/main/java/tree/Statement/Synchronized.java delete mode 100644 src/main/java/tree/Statement/Throw.java delete mode 100644 src/main/java/tree/Statement/Try.java delete mode 100644 src/main/java/tree/Statement/While.java delete mode 100644 src/main/java/tree/Statement/Yield.java delete mode 100644 src/main/java/tree/Type/PrimitiveType.java delete mode 100644 src/main/java/tree/Type/Type.java delete mode 100644 src/main/java/tree/Type/TypeArgument.java delete mode 100644 src/main/java/tree/Type/TypeArguments.java delete mode 100644 src/main/java/tree/Type/TypeList.java delete mode 100644 src/main/java/tree/Type/TypeName.java delete mode 100644 src/main/java/tree/Type/TypeParameter.java delete mode 100644 src/main/java/tree/Type/TypeParameterTail.java delete mode 100644 src/main/java/tree/Type/TypeParameters.java delete mode 100644 src/main/java/tree/Type/UnannotatedType.java diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 9268eadd..901ccc38 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -5,22 +5,35 @@ import lexer.TokenCode import org.antlr.v4.runtime.tree.TerminalNode import parser.JavaParser.* import tree.* -import tree.Compilation.* +import tree.Compilation.CompilationUnit +import tree.Compilation.SimpleCompilationUnit +import tree.Compilation.TopLevelComponent +import tree.Compilation.TopLevelComponents +import tree.Compilation.Package import tree.Declaration.* -import tree.Expression.* -//import tree.Expression.Primary.FieldAccess -import tree.Expression.Primary.Literal -import tree.Expression.Primary.MethodInvocation -import tree.Expression.Primary.This +import tree.Expression.ArgumentList +import tree.Expression.Expression +import tree.Expression.Primary.* +import tree.Expression.SimpleReference import tree.Statement.* import tree.Type.* -import kotlin.reflect.typeOf -fun CompilationUnitContext.toCompilationUnit() : CompilationUnit = - SimpleCompilationUnit( - ImportDeclarations(ArrayList(importDeclaration().map { it.toImportDeclaration() })), - TopLevelComponents(ArrayList(typeDeclaration().mapNotNull { it.toTopLevelComponent() })) // FIXME: should be no nulls +fun CompilationUnitContext.toCompilationUnit() : CompilationUnit { + val imports = ArrayList(importDeclaration().map { it.toImportDeclaration() }) + val importDecls = ImportDeclarations(imports.removeFirstOrNull()) + imports.forEach { importDecls.add(it) } + importDecls.imports.removeIf { it == null } + + val typeDecls = ArrayList(typeDeclaration().mapNotNull { it.toTopLevelComponent() }) // FIXME: should be no nulls + val topLevelCmpnts = TopLevelComponents(typeDecls.removeFirstOrNull()) + typeDecls.forEach { topLevelCmpnts.add(it) } + topLevelCmpnts.components.removeIf { it == null } + + return SimpleCompilationUnit( + importDecls, + topLevelCmpnts ) +} fun TypeDeclarationContext.toTopLevelComponent() : TopLevelComponent? = if (classDeclaration() != null) { @@ -38,18 +51,21 @@ fun ClassDeclarationContext.toClassDeclaration() : ClassDeclaration = classBody().toDeclarations() ) -fun ClassBodyContext.toDeclarations() : Declarations = - Declarations(ArrayList(this.classBodyDeclaration().map { it.toDeclaration() }.filterNotNull())) +fun ClassBodyContext.toDeclarations() : Declarations { + val clsBodyDecls = ArrayList(this.classBodyDeclaration().mapNotNull { it.toDeclaration() }) + val decls = Declarations(clsBodyDecls.removeFirstOrNull()) + clsBodyDecls.forEach { decls.add(it) } + decls.declarations.removeIf { it == null } + return decls +} fun ClassBodyDeclarationContext.toDeclaration() : Declaration? = memberDeclaration()?.toDeclaration(modifier()) ?: block()?.toDeclaration(STATIC()) - ?: null fun MemberDeclarationContext.toDeclaration(modifiers : List?) : Declaration? = methodDeclaration()?.toDeclaration() // FIXME: support other declarations - ?: null fun MethodDeclarationContext.toDeclaration() : Declaration = MethodDeclaration( @@ -64,13 +80,18 @@ fun MethodDeclarationContext.toDeclaration() : Declaration = ) fun MethodBodyContext.toBlock() : Block = - block()?.toBlock() ?: Block(ArrayList(), BlockStatements(ArrayList())) + block()?.toBlock() ?: Block(ArrayList(), BlockStatements(null)) fun FormalParametersContext.toParameterDeclarations() : ParameterDeclarations? = formalParameterList()?.toParameterDeclarations() -fun FormalParameterListContext.toParameterDeclarations() : ParameterDeclarations = - ParameterDeclarations(ArrayList(formalParameter().map { it.toParameterDeclaration() })) +fun FormalParameterListContext.toParameterDeclarations() : ParameterDeclarations { + val formalParams = ArrayList(formalParameter().map { it.toParameterDeclaration() }) + val paramDecls = ParameterDeclarations(formalParams.removeFirstOrNull()) + formalParams.forEach { paramDecls.add(it) } + paramDecls.parameters.removeIf { it == null } + return paramDecls +} fun FormalParameterContext.toParameterDeclaration() : ParameterDeclaration = ParameterDeclaration( @@ -87,13 +108,18 @@ fun TypeTypeOrVoidContext.toType() : Type? = typeType()?.toType() fun BlockContext.toDeclaration(isStatic : TerminalNode?) : Declaration = ClassInitializer(this.toBlock(), isStatic != null) -fun BlockContext.toBlock() : Block = - Block(null /* TODO: always null? */, BlockStatements(ArrayList(this.blockStatement().map { it.toBlockStatement() }))) +fun BlockContext.toBlock(): Block { + val blockStmntsLst = ArrayList(this.blockStatement().map { it.toBlockStatement() }) + val blockStmnts = BlockStatements(blockStmntsLst.removeFirstOrNull()) + blockStmntsLst.forEach { blockStmnts.add(it) } + blockStmnts.blockStatements.removeIf { it == null } + return Block(null /* TODO: always null? */, blockStmnts) +} fun Declaration.toBlockStatement() : BlockStatement = BlockStatement(this) fun Statement.toBlockStatement() : BlockStatement = BlockStatement(this) -fun BlockStatementContext.toBlockStatement() : BlockStatement? = +fun BlockStatementContext.toBlockStatement() : BlockStatement = localVariableDeclaration()?.toDeclaration()?.toBlockStatement() ?: statement()?.toStatement()?.toBlockStatement() ?: localTypeDeclaration()?.toDeclaration()?.toBlockStatement() @@ -156,7 +182,6 @@ fun SwitchLabelContext.toSwitchLabel() : SwitchLabel = SwitchLabel( constantExpression?.toExpression() ?: enumConstantName?.toCompoundName()?.toExpression() - ?: null ) fun org.antlr.v4.runtime.Token.toCompoundName() : CompoundName = CompoundName(text) @@ -193,19 +218,17 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = fun CompoundName.toExpression() : Expression = SimpleReference(this) -fun ExpressionContext.toExpression() : Expression = +fun ExpressionContext.toExpression() : Expression { + val expr0 = + expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() + ?: creator()?.toExpression() ?: methodCall()?.toExpression(null) ?: + SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ if (this.bop != null) { - val expr0 = - expression(0)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() val expr1 = - expression(1)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() ?: - methodCall()?.toExpression(expr0) ?: - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ - if (this.bop.text == ".") { + expression(1)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() + ?: creator()?.toExpression() ?: methodCall()?.toExpression(expr0) + ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + return if (this.bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 is SimpleReference -> FieldAccess( @@ -218,49 +241,67 @@ fun ExpressionContext.toExpression() : Expression = } else { SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } - // if (expression(1) != null && expression(2) == null) { - // Binary(expression(0).toExpression(), expression(1).toExpression(), bop.toToken()) - // } else { - // SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ - // } } else { - expression(0)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() ?: - methodCall()?.toExpression(null) ?: - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + return expr0 } +} -fun MethodCallContext.toExpression(expr: Expression?) : Expression { - val args = ArgumentList( - if (expressionList() == null) - listOf() - else - expressionList().expression().stream().map { it.toExpression() }.toList() +fun CreatorContext.toExpression() : Expression { + return InstanceCreation( + null, // No type arguments for now + TypeName( + CompoundName(createdName().identifier().map { it.IDENTIFIER().text }.toList()), + null // No type arguments for now + ), + classCreatorRest().arguments()?.toArgList(), + classCreatorRest().classBody()?.toDeclarations() ) +} + +fun ArgumentsContext.toArgList() : ArgumentList { + return if (expressionList() == null) { + ArgumentList(null) + } else { + val argsLst = ArrayList(expressionList().expression().map { it.toExpression() }.toList()) + val args = ArgumentList(argsLst.removeFirstOrNull()) + argsLst.forEach { args.add(it) } + args.arguments.removeIf { it == null } + args + } +} + +fun MethodCallContext.toExpression(expr: Expression?) : Expression { + val exprLst = if (expressionList() == null) + ArrayList(listOf()) + else + ArrayList(expressionList().expression().stream().map { it.toExpression() }.toList()) + val argList = ArgumentList(exprLst.removeFirstOrNull()) + exprLst.forEach { argList.add(it) } + argList.arguments.removeIf { it == null } return MethodInvocation( expr, SUPER() != null, null, // TODO: type arguments are somewhere else identifier().toToken(), - args + argList ) } fun IdentifierContext.toExpression() : Expression = SimpleReference(CompoundName(IDENTIFIER().text)) -fun PrimaryContext.toExpression() : Expression? = +fun PrimaryContext.toExpression() : Expression = expression()?.toExpression() ?: identifier()?.toExpression() ?: THIS()?.let { _ -> This(null) } ?: /* FIXME: super */ literal()?.toLiteral() ?: - identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } + identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } ?: + SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ /* FIXME: typeOrVoid . CLASS */ /* FIXME: nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) */ -fun LiteralContext.toLiteral() : Literal? = +fun LiteralContext.toLiteral() : Literal = BOOL_LITERAL()?.text?.let { txt -> Literal(Token(if (txt == "true") { TokenCode.True } else { TokenCode.False })) } ?: integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text))} ?: NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } ?: @@ -269,7 +310,7 @@ fun LiteralContext.toLiteral() : Literal? = Literal(Token(TokenCode.IntegerLiteral, "123456")) ?: /* FIXME: support other literals */ throw Exception("unsupported literal $text") /* FIXME */ -fun LocalVariableDeclarationContext.toDeclaration() : Declaration? = +fun LocalVariableDeclarationContext.toDeclaration() : Declaration = TypeAndDeclarators( typeType()?.toType(), if (identifier() != null) { @@ -285,31 +326,54 @@ fun IdentifierContext.toVariableDeclarators(expression : ExpressionContext) : Va fun IdentifierContext.toVariableDeclarator(expression : ExpressionContext) : VariableDeclarator = VariableDeclarator(this.toToken(), null, InitializerSimple(expression.toExpression())) -fun VariableDeclaratorsContext.toVariableDeclarators() : VariableDeclarators = - VariableDeclarators(ArrayList(this.variableDeclarator().map { it.toVariableDeclarator() })) +fun VariableDeclaratorsContext.toVariableDeclarators() : VariableDeclarators { + val varDeclsLst = ArrayList(this.variableDeclarator().map { it.toVariableDeclarator() }) + val varDecls = VariableDeclarators(varDeclsLst.removeFirstOrNull()) + varDeclsLst.forEach { varDecls.add(it) } + varDecls.declarators.removeIf { it == null } + return varDecls +} -fun VariableDeclaratorContext.toVariableDeclarator() : VariableDeclarator = - VariableDeclarator( - this.variableDeclaratorId().identifier().toToken(), - Dims(ArrayList(variableDeclaratorId().LBRACK().size)), - this.variableInitializer()?.toInitializer() +fun VariableDeclaratorContext.toVariableDeclarator() : VariableDeclarator { + // val dimLst = ArrayList(variableDeclaratorId().LBRACK().size) + val dims = Dims() + return VariableDeclarator( + this.variableDeclaratorId().identifier().toToken(), + dims, + this.variableInitializer()?.toInitializer() ) +} fun VariableInitializerContext.toInitializer() : Initializer = arrayInitializer()?.toInitializerArray() ?: InitializerSimple(expression().toExpression()) -fun ArrayInitializerContext.toInitializerArray() : InitializerArray = - InitializerArray(ArrayList(variableInitializer().map { it.toInitializer() })) +fun ArrayInitializerContext.toInitializerArray() : InitializerArray { + val varInitLst = ArrayList(variableInitializer().map { it.toInitializer() }) + val initArr = InitializerArray(varInitLst.removeFirstOrNull()) + varInitLst.forEach { initArr.add(it) } + initArr.initializers.removeIf { it == null } + return initArr +} -fun TypeParametersContext.toTypeParameters() : TypeParameters = - TypeParameters(ArrayList(this.typeParameter().map { it.toTypeParameter()})) +fun TypeParametersContext.toTypeParameters() : TypeParameters { + val typeLst = ArrayList(this.typeParameter().map { it.toTypeParameter()}) + val typeParams = TypeParameters(typeLst.removeFirstOrNull()) + typeLst.forEach { typeParams.add(it) } + typeParams.typeParameters.removeIf { it == null } + return typeParams +} fun TypeParameterContext.toTypeParameter() : TypeParameter = TypeParameter(null /* FIXME */, TypeParameterTail(this.identifier().toToken(), null /* FIXME */)) -fun TypeListContext.toTypeList() : TypeList = - TypeList(ArrayList(this.typeType().map { it.toType() })) +fun TypeListContext.toTypeList() : TypeList { + val typeArr = ArrayList(this.typeType().map { it.toType() }) + val typeLst = TypeList(typeArr.removeFirstOrNull()) + typeArr.forEach { typeLst.add(it) } + typeLst.types.removeIf { it == null } + return typeLst +} fun TypeTypeContext.toType() : Type = when (this) { @@ -321,7 +385,7 @@ fun TypeTypeContext.toType() : Type = fun TypePrimitiveTypeContext.toType() : Type = primitiveType().toType() // FIXME: annotations and more? -fun TerminalNode.toPrimitiveType() : PrimitiveType? = +fun TerminalNode.toPrimitiveType() : PrimitiveType = when (this.symbol.type) { BOOLEAN -> PrimitiveType(Token(TokenCode.Boolean)) CHAR -> PrimitiveType(Token(TokenCode.Char)) @@ -353,8 +417,13 @@ fun ClassOrInterfaceTypeContext.toType() : Type = this.typeArguments().lastOrNull()?.toTypeArguments() // FIXME: we use last() since we do not support types like A.C ) -fun TypeArgumentsContext.toTypeArguments() : TypeArguments = - TypeArguments(ArrayList(typeArgument().map { it.toTypeArgument() })) +fun TypeArgumentsContext.toTypeArguments() : TypeArguments { + val typeArgsLst = ArrayList(typeArgument().map { it.toTypeArgument() }) + val typeArgs = TypeArguments(typeArgsLst.removeFirstOrNull()) + typeArgsLst.forEach { typeArgs.add(it) } + typeArgs.arguments.removeIf { it == null } + return typeArgs +} fun TypeArgumentContext.toTypeArgument() : TypeArgument = TypeArgument(typeType()?.toType(), 0 /* FIXME */, null) diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index dae0778e..f68d574f 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -2,15 +2,10 @@ package translator import arrow.core.None import eotree.* -import eotree.data.EOIntData import lexer.TokenCode import tree.Expression.Binary import tree.Expression.Expression -import tree.Expression.FieldAccess -import tree.Expression.Primary.Literal -import tree.Expression.Primary.MethodInvocation -import tree.Expression.Primary.Parenthesized -import tree.Expression.Primary.This +import tree.Expression.Primary.* import tree.Expression.SimpleReference import tree.Expression.UnaryPostfix import tree.Expression.UnaryPrefix diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index 366502fe..82db059d 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -8,13 +8,11 @@ import eotree.EOExpr import eotree.EOObject import eotree.eoDot import tree.CompoundName -import tree.Expression.Expression -import tree.Expression.FieldAccess +import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import util.ParseExprTasks import util.isSystemOutCall -import java.lang.reflect.Field // TODO: create state object to store binding of expression fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: MethodInvocation): EOObject { diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index 5e6136c1..afe63202 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -7,7 +7,7 @@ import tree.Compilation.TopLevelComponent import tree.CompoundName import tree.Declaration.* import tree.Expression.Expression -import tree.Expression.FieldAccess +import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import tree.InitializerSimple diff --git a/src/main/java/tree/AnnoElementValue.java b/src/main/java/tree/AnnoElementValue.java deleted file mode 100644 index b5706b7a..00000000 --- a/src/main/java/tree/AnnoElementValue.java +++ /dev/null @@ -1,4 +0,0 @@ -package tree; - -public class AnnoElementValue extends Entity { -} diff --git a/src/main/java/tree/AnnoParameterList.java b/src/main/java/tree/AnnoParameterList.java deleted file mode 100644 index 9fdedbf6..00000000 --- a/src/main/java/tree/AnnoParameterList.java +++ /dev/null @@ -1,21 +0,0 @@ -package tree; - -// AnnoParameterList -// : IDENTIFIER EQUAL ElementValue -// | AnnoParameterList COMMA IDENTIFIER EQUAL ElementValue -// ; -// -// ElementValue -// : ConditionalExpression -// | LBRACE ElementValueListOpt RBRACE -// | LBRACE COMMA RBRACE -// | Annotation -// ; -// -// ElementValueListOpt -// : //empty -// | ElementValue -// | ElementValueListOpt COMMA ElementValue -// ; -public class AnnoParameterList extends Entity { -} diff --git a/src/main/java/tree/Annotation.java b/src/main/java/tree/Annotation.java deleted file mode 100644 index f2dce8d5..00000000 --- a/src/main/java/tree/Annotation.java +++ /dev/null @@ -1,46 +0,0 @@ -package tree; - -// Annotation -// : AT CompoundName -// | AT CompoundName LPAREN RPAREN -// | AT CompoundName LPAREN AnnoParameterList RPAREN -// | AT CompoundName LPAREN ElementValue RPAREN -// ; -public class Annotation extends Entity { - // Structure - public CompoundName compoundName; - public AnnoParameterList annoParameterList; - - // Creation - public Annotation(CompoundName cn, AnnoParameterList apl) { - this.compoundName = cn; - this.annoParameterList = apl; - - if (this.compoundName != null) { - this.compoundName.parent = this; - } - if (this.annoParameterList != null) { - this.annoParameterList.parent = this; - } - } - - public Annotation(CompoundName cn, AnnoElementValue aev) { - this.compoundName = cn; - this.annoParameterList = new AnnoParameterList(); - // this.annoParameterList.add - - if (this.compoundName != null) { - this.compoundName.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.print("ANNOTATION "); - compoundName.report(0); - System.out.println(); - annoParameterList.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Annotations.java b/src/main/java/tree/Annotations.java deleted file mode 100644 index bb53b45f..00000000 --- a/src/main/java/tree/Annotations.java +++ /dev/null @@ -1,33 +0,0 @@ -package tree; - -import java.util.ArrayList; - -public class Annotations extends Entity { - // Structure - public ArrayList annotations; - - // Creation - public Annotations(Annotation ann) { - this.annotations = new ArrayList(); - this.annotations.add(ann); - if (ann != null) { - ann.parent = this; - } - } - - public Annotations add(Annotation ann) { - this.annotations.add(ann); - if (ann != null) { - ann.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (Annotation ann : annotations) { - ann.report(sh); - } - } - -} diff --git a/src/main/java/tree/Compilation/CompilationUnit.java b/src/main/java/tree/Compilation/CompilationUnit.java deleted file mode 100644 index 14538c7e..00000000 --- a/src/main/java/tree/Compilation/CompilationUnit.java +++ /dev/null @@ -1,12 +0,0 @@ -package tree.Compilation; - -import tree.Entity; - -// CompilationUnit -// : // empty -// | Package -// | Module -// | ImportDeclarationSeqOpt TopLevelComponentSeq -// ; -public class CompilationUnit extends Entity { -} diff --git a/src/main/java/tree/Compilation/Module.java b/src/main/java/tree/Compilation/Module.java deleted file mode 100644 index bc9c3945..00000000 --- a/src/main/java/tree/Compilation/Module.java +++ /dev/null @@ -1,5 +0,0 @@ -package tree.Compilation; - -public class Module extends CompilationUnit { -} - diff --git a/src/main/java/tree/Compilation/Package.java b/src/main/java/tree/Compilation/Package.java deleted file mode 100644 index a40e8f3a..00000000 --- a/src/main/java/tree/Compilation/Package.java +++ /dev/null @@ -1,44 +0,0 @@ -package tree.Compilation; - -import tree.CompoundName; -import tree.Declaration.ImportDeclarations; -import tree.Entity; - -// Package -// : PACKAGE CompoundName SEMICOLON ImportDeclarationSeqOpt TopLevelComponentSeqOpt -// ; -public class Package extends CompilationUnit { - // Structure - public CompoundName compoundName; - public ImportDeclarations imports; - public TopLevelComponents components; - - // Creation - public Package(CompoundName cn, ImportDeclarations ims, TopLevelComponents cs) { - this.compoundName = cn; - this.imports = ims; - this.components = cs; - - if (this.compoundName != null) { - this.compoundName.parent = this; - } - if (this.imports != null) { - this.imports.parent = this; - } - if (this.components != null) { - this.components.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.print("PACKAGE "); - compoundName.report(0); - System.out.println(); - - imports.report(sh); - components.report(sh); - } - -} diff --git a/src/main/java/tree/Compilation/SimpleCompilationUnit.java b/src/main/java/tree/Compilation/SimpleCompilationUnit.java deleted file mode 100644 index 48328d12..00000000 --- a/src/main/java/tree/Compilation/SimpleCompilationUnit.java +++ /dev/null @@ -1,39 +0,0 @@ -package tree.Compilation; - -import tree.Declaration.ImportDeclarations; - -// CompilationUnit -// : %empty -// | Package -// | Module -// | ImportDeclarationSeqOpt TopLevelComponentSeq <===== -// ; -public class SimpleCompilationUnit extends CompilationUnit { - // Structure - public ImportDeclarations imports; - public TopLevelComponents components; - - // Creation - public SimpleCompilationUnit(ImportDeclarations ids, TopLevelComponents tlcs) { - this.imports = ids; - this.components = tlcs; - - if (this.imports != null) { - this.imports.parent = this; - } - if (this.components != null) { - this.components.parent = this; - } - } - - // Reporting - public void report(int sh) { - if (imports != null) { - imports.report(sh); - } - if (components != null) { - components.report(sh); - } - } - -} diff --git a/src/main/java/tree/Compilation/TopLevelComponent.java b/src/main/java/tree/Compilation/TopLevelComponent.java deleted file mode 100644 index 59c3ada1..00000000 --- a/src/main/java/tree/Compilation/TopLevelComponent.java +++ /dev/null @@ -1,53 +0,0 @@ -package tree.Compilation; - -import tree.Declaration.ClassDeclaration; -import tree.Declaration.Declaration; -import tree.Declaration.InterfaceDeclaration; -import tree.Entity; -import tree.Modifiers; - -// TopLevelComponent -// : ClassDeclaration -// | InterfaceDeclaration -// ; -public class TopLevelComponent extends Entity { - // Structure: either first OR second - public ClassDeclaration classDecl; - public InterfaceDeclaration interfaceDecl; - - // Creation - public TopLevelComponent(ClassDeclaration cd) { - this.classDecl = cd; - this.interfaceDecl = null; - - if (this.classDecl != null) { - this.classDecl.parent = this; - } - } - - public TopLevelComponent(InterfaceDeclaration id) { - this.interfaceDecl = id; - - if (this.interfaceDecl != null) { - this.interfaceDecl.parent = this; - } - } - - public void addModifiers(Modifiers mods) { - Declaration decl = classDecl != null ? classDecl : interfaceDecl; - decl.modifiers = mods; - if (decl != null) { - decl.parent = this; - } - } - - // Reporting - public void report(int sh) { - if (this.classDecl != null) { - this.classDecl.report(sh); - } else { - this.interfaceDecl.report(sh); - } - } - -} diff --git a/src/main/java/tree/Compilation/TopLevelComponents.java b/src/main/java/tree/Compilation/TopLevelComponents.java deleted file mode 100644 index a653e4b6..00000000 --- a/src/main/java/tree/Compilation/TopLevelComponents.java +++ /dev/null @@ -1,47 +0,0 @@ -package tree.Compilation; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import tree.Entity; - -// TopLevelComponentSeq -// : ModifierSeqOpt TopLevelComponent -// | TopLevelComponentSeq ModifierSeqOpt TopLevelComponent -// ; -public class TopLevelComponents extends Entity { - // Structure - public ArrayList components; - - // Creation - public TopLevelComponents(TopLevelComponent tlc) { - this.components = new ArrayList<>(); - this.components.add(tlc); - - if (tlc != null) { - tlc.parent = this; - } - } - - public TopLevelComponents(ArrayList components) { - this.components = components; - for (var tlc : components) { - tlc.parent = this; - } - } - - public TopLevelComponents add(TopLevelComponent tlc) { - this.components.add(tlc); - if (tlc != null) { - tlc.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (TopLevelComponent tlc : components) { - tlc.report(sh); - } - } - -} diff --git a/src/main/java/tree/CompoundName.java b/src/main/java/tree/CompoundName.java deleted file mode 100644 index 555195dc..00000000 --- a/src/main/java/tree/CompoundName.java +++ /dev/null @@ -1,51 +0,0 @@ -package tree; - -import java.util.ArrayList; -import java.util.List; - -// %nterm CompoundName -// -// CompoundName -// : IDENTIFIER { $$ = new CompoundName($1.image); } -// | CompoundName DOT IDENTIFIER { $$ = $1.add($3.image); } -// ; -public class CompoundName extends Entity { - // Structure - public ArrayList names; - - // Creation - public CompoundName(String first) { - names = new ArrayList<>(); - names.add(first); - } - - public CompoundName(List name) { - names = new ArrayList<>(name); - } - - // Adding - public CompoundName add(String next) { - names.add(next); - return this; - } - - public String concatenatedJava() { - return String.join(".", names); - } - - public String concatenatedEO() { - return String.join("__", names); - } - - // Reporting - public void report(int sh) { - // Entity.doShift(sh); - for (int i = 0; i < names.size(); i++) { - System.out.print(names.get(i)); - if (i < names.size() - 1) { - System.out.print("."); - } - } - } - -} diff --git a/src/main/java/tree/Declaration/CatchParameter.java b/src/main/java/tree/Declaration/CatchParameter.java deleted file mode 100644 index 7b63f4d9..00000000 --- a/src/main/java/tree/Declaration/CatchParameter.java +++ /dev/null @@ -1,44 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Dims; -import tree.Modifiers; -import tree.Type.TypeList; - -// CatchFormalParameter -// : ModifierSeqOpt CatchType IDENTIFIER DimsOpt -// ; -// -//CatchType -// : Type -// | CatchType VERTICAL Type -// ; -public class CatchParameter extends ParameterDeclaration { - // Structure - - // From the base class: - // public Modifiers modifiers; - // public Type type; -- not used here - // public String name; - // public Annotations ellAnnotations; -- not used here - // public boolean signEllipsis; -- not used here - // public Dims dims; - // Own attributes: - public TypeList catchTypes; - - // Creation - public CatchParameter(Modifiers mods, TypeList types, Token id, Dims dims) { - super(mods, null, id.image, null, false, dims); - this.catchTypes = types; - - if (this.catchTypes != null) { - this.catchTypes.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/ClassDeclaration.java b/src/main/java/tree/Declaration/ClassDeclaration.java deleted file mode 100644 index d9303d0e..00000000 --- a/src/main/java/tree/Declaration/ClassDeclaration.java +++ /dev/null @@ -1,21 +0,0 @@ -package tree.Declaration; - -import tree.Modifiers; - -// ClassDeclaration -// : NormalClassDeclaration -// | EnumDeclaration -// | RecordDeclaration -// ; -public class ClassDeclaration extends Declaration { - // NO structure - - // Creation - public ClassDeclaration(Modifiers mods, String n) { - super(mods, n, null); - } - - // NO reporting - - // NO generation -} diff --git a/src/main/java/tree/Declaration/ClassInitializer.java b/src/main/java/tree/Declaration/ClassInitializer.java deleted file mode 100644 index 35a0232e..00000000 --- a/src/main/java/tree/Declaration/ClassInitializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Declaration; - -import tree.Statement.Block; - -// ClassBodyDeclaration -// : ... -// | Block // InstanceInitializer -// | STATIC Block // StaticInitializer -// | ... -// ; -public class ClassInitializer extends Declaration { - // Structure - public Block block; - public boolean signStatic; - - // Creation - public ClassInitializer(Block b, boolean ss) { - super(null, null, null); - this.block = b; - this.signStatic = ss; - - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/ConstructorBody.java b/src/main/java/tree/Declaration/ConstructorBody.java deleted file mode 100644 index e436ddcb..00000000 --- a/src/main/java/tree/Declaration/ConstructorBody.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Statement.Block; - -// ConstructorBody -// : LBRACE RBRACE -// | LBRACE ExplicitConstructorInvocation RBRACE -// | LBRACE BlockStatementSeq RBRACE -// | LBRACE ExplicitConstructorInvocation BlockStatementSeq RBRACE -// ; -public class ConstructorBody extends Entity { - // Structure - public ExplicitConstructorInvocation invocation; - public Block block; - - // Creation - public ConstructorBody(ExplicitConstructorInvocation inv, Block block) { - this.invocation = inv; - this.block = block; - - if (this.invocation != null) { - this.invocation.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/ConstructorDeclaration.java b/src/main/java/tree/Declaration/ConstructorDeclaration.java deleted file mode 100644 index e027d3d5..00000000 --- a/src/main/java/tree/Declaration/ConstructorDeclaration.java +++ /dev/null @@ -1,55 +0,0 @@ -package tree.Declaration; - -import tree.Modifiers; -import tree.Statement.Block; -import tree.Type.TypeList; -import tree.Type.TypeParameters; - -// ConstructorDeclaration -// : /*ModifierSeqOpt*/ ConstructorDeclarator ThrowsOpt ConstructorBody -// ; -// -//ConstructorDeclarator -// : TypeParametersOpt IDENTIFIER LPAREN FormalParameterList/*FormalParameters*/ RPAREN -// ; -// -//ConstructorBody -// : LBRACE RBRACE -// | LBRACE ExplicitConstructorInvocation RBRACE -// | LBRACE BlockStatementSeq RBRACE -// | LBRACE ExplicitConstructorInvocation BlockStatementSeq RBRACE -// ; -public class ConstructorDeclaration extends MethodDeclaration { - // Structure: all from the base class - // public Modifiers modifiers; - // public TypeParameters typeParameters; - // public Type type; // always null - // public String name; // always null - // public ReceiverDeclaration receiver; - // public ParameterDeclarations parameters; - // public Dims dims; // always null - // public TypeList exceptions; - public ExplicitConstructorInvocation invocation; - // public Block methodBody; - - // Creation - public ConstructorDeclaration(Modifiers mods, - TypeParameters typePars, - ParameterDeclarations pars, - TypeList excs, - ExplicitConstructorInvocation inv, - Block body) { - super(mods, typePars, null, null, pars, null, excs, body); - this.invocation = inv; - - if (this.invocation != null) { - this.invocation.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("CONSTRUCTOR", sh); - } - -} diff --git a/src/main/java/tree/Declaration/ConstructorDeclarator.java b/src/main/java/tree/Declaration/ConstructorDeclarator.java deleted file mode 100644 index be7870f3..00000000 --- a/src/main/java/tree/Declaration/ConstructorDeclarator.java +++ /dev/null @@ -1,34 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Type.TypeParameters; - -// Intermediate class: won't appear in the AST. -// -// ConstructorDeclarator -// : TypeParametersOpt IDENTIFIER LPAREN FormalParameterList/*FormalParameters*/ RPAREN -// ; -public class ConstructorDeclarator extends Entity { - // Structure - public TypeParameters typeParameters; - public ParameterDeclarations formalParameters; - - // Creation - public ConstructorDeclarator(TypeParameters tpars, ParameterDeclarations pars) { - this.typeParameters = tpars; - this.formalParameters = pars; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.formalParameters != null) { - this.formalParameters.parent = this; - } - } - - // Reporting - public void report(int sh) { - // Empty - } - -} diff --git a/src/main/java/tree/Declaration/Declaration.java b/src/main/java/tree/Declaration/Declaration.java deleted file mode 100644 index 58aee7e0..00000000 --- a/src/main/java/tree/Declaration/Declaration.java +++ /dev/null @@ -1,72 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Modifiers; -import tree.Type.Type; - -// ClassDeclaration -// : NormalClassDeclaration -// | EnumDeclaration -// | RecordDeclaration -// ; -// -// ClassBodyDeclaration -// : ModifierSeqOpt PureBodyDeclaration -// | Block // InstanceInitializer -// | STATIC Block // StaticInitializer -// | SEMICOLON -// ; -// -// PureBodyDeclaration -// : FieldDeclaration -// | MethodDeclaration -// | ClassDeclaration -// | InterfaceDeclaration -// | ConstructorDeclaration -// ; -// -// BlockDeclaration -// : ClassDeclaration -// | NormalInterfaceDeclaration -// | LocalVariableDeclaration SEMICOLON -// ; -// -//LocalVariableDeclaration -// : UnannotatedType VariableDeclaratorList -// | VAR VariableDeclaratorList -// ; -public class Declaration extends Entity { - // Structure: properties common to (almost) all - // kinds of declarations. - public Modifiers modifiers; - public String name; - public Type type; - - // Creation - public Declaration(Modifiers mods, String n, Type t) { - this.modifiers = mods; - this.name = n; - this.type = t; - - if (this.modifiers != null) { - this.modifiers.parent = this; - } - if (this.type != null) { - this.type.parent = this; - } - } - - public Declaration addModifiers(Modifiers mods) { - this.modifiers = mods; - if (this.modifiers != null) { - this.modifiers.parent = this; - } - return this; - } - - // Reporting - public void report(int sg) { - - } - -} diff --git a/src/main/java/tree/Declaration/Declarations.java b/src/main/java/tree/Declaration/Declarations.java deleted file mode 100644 index a76b8496..00000000 --- a/src/main/java/tree/Declaration/Declarations.java +++ /dev/null @@ -1,54 +0,0 @@ -package tree.Declaration; - -import java.util.ArrayList; -import tree.Entity; - -public class Declarations extends Entity { - // Structure - public ArrayList declarations; - - // Creation - public Declarations(Declaration d) { - this.declarations = new ArrayList<>(); - deconstruct(d); - } - - public Declarations(ArrayList declarations) { - this.declarations = new ArrayList<>(); - for (var d : declarations){ - deconstruct(d); - } - } - - public Declarations add(Declaration d) { - deconstruct(d); - return this; - } - - private void deconstruct(Declaration d) { - if (d instanceof TypeAndDeclarators) { - TypeAndDeclarators tds = (TypeAndDeclarators) d; - for (VariableDeclarator declarator : tds.declarators.declarators) { - VariableDeclaration variable = - new VariableDeclaration(declarator.name, d.modifiers, d.type, declarator.dims, declarator.initializer); - this.declarations.add(variable); - if (variable != null) { - variable.parent = this; - } - } - } else { - this.declarations.add(d); - if (d != null) { - d.parent = this; - } - } - } - - // Reporting - public void report(int sh) { - for (Declaration d : declarations) { - d.report(sh); - } - } - -} diff --git a/src/main/java/tree/Declaration/EnumBody.java b/src/main/java/tree/Declaration/EnumBody.java deleted file mode 100644 index a68cbf0a..00000000 --- a/src/main/java/tree/Declaration/EnumBody.java +++ /dev/null @@ -1,33 +0,0 @@ -package tree.Declaration; - -import tree.Entity; - -// This is intermediate class -- won't appear in the AST -// -// EnumBody -// : LBRACE EnumConstantListOpt EnumBodyDeclarationsOpt RBRACE -// | LBRACE EnumConstantListOpt COMMA EnumBodyDeclarationsOpt RBRACE -// ; -public class EnumBody extends Entity { - // Structure - public Enumerators enumerators; - public Declarations declarations; - - // Creation - public EnumBody(Enumerators ens, Declarations decls) { - this.enumerators = ens; - this.declarations = decls; - - if (this.enumerators != null) { - this.enumerators.parent = this; - } - if (this.declarations != null) { - this.declarations.parent = this; - } - } - - // Reporting - public void report(int sh) { - // Empty; not needed - } -} diff --git a/src/main/java/tree/Declaration/EnumDeclaration.java b/src/main/java/tree/Declaration/EnumDeclaration.java deleted file mode 100644 index 65b56b6f..00000000 --- a/src/main/java/tree/Declaration/EnumDeclaration.java +++ /dev/null @@ -1,78 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Entity; -import tree.Type.TypeList; - -// EnumDeclaration -// : /*ModifierSeqOpt*/ ENUM IDENTIFIER ClassImplementsOpt EnumBody -// ; -// -//EnumBody -// : LBRACE EnumConstantListOpt EnumBodyDeclarationsOpt RBRACE -// | LBRACE EnumConstantListOpt COMMA EnumBodyDeclarationsOpt RBRACE -// ; -// -//EnumConstantListOpt -// : // empty -// | EnumConstant -// | EnumConstantListOpt COMMA EnumConstant -// ; -// -//EnumConstant -// : AnnotationSeqOpt IDENTIFIER Arguments -// | AnnotationSeqOpt IDENTIFIER Arguments ClassBody -// ; -// -//EnumBodyDeclarationsOpt -// : // empty -// | SEMICOLON -// | SEMICOLON ClassBodyDeclarationSeq -// ; -public class EnumDeclaration extends ClassDeclaration { - // Structure - // public Modifiers modifiers; -- in the base class - // public String name; -- in the base class - public TypeList implemented; - public Enumerators enumerators; - public Declarations body; - - // Creation - public EnumDeclaration(Token n, TypeList impls, EnumBody body) { - super(null, n.image); - this.implemented = impls; - this.enumerators = body.enumerators; - this.body = body.declarations; - - if (this.implemented != null) { - this.implemented.parent = this; - } - if (this.enumerators != null) { - this.enumerators.parent = this; - } - if (this.body != null) { - this.body.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("ENUM DECLARATION " + name, sh); - if (implemented != null) { - Entity.doShift(sh + Entity.shift); - System.out.println("BASES:"); - implemented.report(sh + 2 * Entity.shift); - } - if (enumerators != null) { - Entity.doShift(sh + Entity.shift); - System.out.println("ENUMERATORS:"); - enumerators.report(sh + 2 * Entity.shift); - } - if (body != null) { - Entity.doShift(sh + Entity.shift); - System.out.println("ENUM BODY:"); - body.report(sh + 2 * Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/Enumerator.java b/src/main/java/tree/Declaration/Enumerator.java deleted file mode 100644 index 8d748b92..00000000 --- a/src/main/java/tree/Declaration/Enumerator.java +++ /dev/null @@ -1,49 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Annotations; -import tree.Entity; -import tree.Expression.ArgumentList; - -// EnumConstant -// : AnnotationSeqOpt IDENTIFIER Arguments -// | AnnotationSeqOpt IDENTIFIER Arguments ClassBody -// ; -public class Enumerator extends Entity { - // Structure - public Annotations annotations; - public String name; - public ArgumentList arguments; - public Declarations enumBody; - - // Creation - public Enumerator(Annotations anns, Token name, ArgumentList args, Declarations body) { - this.annotations = anns; - this.name = name.image; - this.arguments = args; - this.enumBody = body; - - if (this.annotations != null) { - this.annotations.parent = this; - } - if (this.arguments != null) { - this.arguments.parent = this; - } - if (this.enumBody != null) { - this.enumBody.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("ENUM CONSTANT " + name, sh); - if (arguments != null) { - Entity.doShift(sh + Entity.shift); - System.out.println("ARGUMENTS:"); - arguments.report(sh + 2 * Entity.shift); - } - if (enumBody != null) { - enumBody.report(sh + Entity.shift); - } - } -} diff --git a/src/main/java/tree/Declaration/Enumerators.java b/src/main/java/tree/Declaration/Enumerators.java deleted file mode 100644 index 31dd7f63..00000000 --- a/src/main/java/tree/Declaration/Enumerators.java +++ /dev/null @@ -1,43 +0,0 @@ -package tree.Declaration; - -import java.util.ArrayList; -import tree.Entity; - -// EnumConstantListOpt -// : %empty -// : EnumConstantList -// ; -// -// EnumConstantList -// : EnumConstant -// | EnumConstantListOpt COMMA EnumConstant -// ; -public class Enumerators extends Entity { - // Structure - public ArrayList enumerators; - - // Creation - public Enumerators(Enumerator en) { - this.enumerators = new ArrayList<>(); - this.enumerators.add(en); - - if (en != null) { - en.parent = this; - } - } - - public Enumerators add(Enumerator en) { - this.enumerators.add(en); - if (en != null) { - en.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (Enumerator e : enumerators) { - e.report(sh); - } - } -} diff --git a/src/main/java/tree/Declaration/ExplicitConstructorInvocation.java b/src/main/java/tree/Declaration/ExplicitConstructorInvocation.java deleted file mode 100644 index a0d641cb..00000000 --- a/src/main/java/tree/Declaration/ExplicitConstructorInvocation.java +++ /dev/null @@ -1,49 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Expression.ArgumentList; -import tree.Expression.Expression; -import tree.Type.TypeArguments; - -// Intermediate class: won't appear in the AST -// -// ExplicitConstructorInvocation -// : TypeArgumentsOpt THIS Arguments SEMICOLON -// | TypeArgumentsOpt SUPER Arguments SEMICOLON -// | CompoundName DOT TypeArgumentsOpt SUPER Arguments SEMICOLON -// | Primary DOT TypeArgumentsOpt SUPER Arguments SEMICOLON -// ; -public class ExplicitConstructorInvocation extends Entity { - // Structure - public Expression expression; - public TypeArguments typeArguments; - public boolean thisORsuper; - public ArgumentList arguments; - - // Creation - public ExplicitConstructorInvocation( - Expression expr, - TypeArguments targs, - boolean ts, ArgumentList args) { - this.expression = expr; - this.typeArguments = targs; - this.thisORsuper = ts; - this.arguments = args; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.typeArguments != null) { - this.typeArguments.parent = this; - } - if (this.arguments != null) { - this.arguments.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/ImportDeclaration.java b/src/main/java/tree/Declaration/ImportDeclaration.java deleted file mode 100644 index 99f4622e..00000000 --- a/src/main/java/tree/Declaration/ImportDeclaration.java +++ /dev/null @@ -1,46 +0,0 @@ -package tree.Declaration; - -import tree.CompoundName; -import tree.Entity; - -// ImportDeclaration -// : IMPORT StaticOpt CompoundName SEMICOLON -// | IMPORT StaticOpt CompoundName DOT STAR SEMICOLON -// ; -// -// StaticOpt -// : // empty -// | STATIC -// ; -public class ImportDeclaration extends Entity { - // Structure - public boolean signStatic; - public CompoundName compoundName; - public boolean signStar; - - // Creation - public ImportDeclaration(boolean stat, CompoundName cn, boolean star) { - this.signStatic = stat; - this.compoundName = cn; - this.signStar = star; - - if (this.compoundName != null) { - this.compoundName.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.print("IMPORT "); - if (this.signStatic) { - System.out.print("STATIC "); - } - compoundName.report(0); - if (this.signStar) { - System.out.print(".*"); - } - System.out.println(); - } - -} diff --git a/src/main/java/tree/Declaration/ImportDeclarations.java b/src/main/java/tree/Declaration/ImportDeclarations.java deleted file mode 100644 index 5fa97cc5..00000000 --- a/src/main/java/tree/Declaration/ImportDeclarations.java +++ /dev/null @@ -1,47 +0,0 @@ -package tree.Declaration; - -import tree.Entity; - -import java.util.ArrayList; - -// ImportDeclarationSeqOpt -// : // empty -// | ImportDeclaration -// | ImportDeclarationSeqOpt ImportDeclaration -// ; -public class ImportDeclarations extends Entity { - // Structure - public ArrayList imports; - - public ImportDeclarations(ArrayList imports) { - this.imports = imports; - - this.imports.stream().findFirst().map(importDeclaration -> importDeclaration.parent = this); - } - - // Creation - public ImportDeclarations(ImportDeclaration id) { - this.imports = new ArrayList<>(); - this.imports.add(id); - - if (id != null) { - id.parent = this; - } - } - - public ImportDeclarations add(ImportDeclaration id) { - imports.add(id); - if (id != null) { - id.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (ImportDeclaration id : imports) { - id.report(sh); - } - } - -} diff --git a/src/main/java/tree/Declaration/InterfaceDeclaration.java b/src/main/java/tree/Declaration/InterfaceDeclaration.java deleted file mode 100644 index 5a02596f..00000000 --- a/src/main/java/tree/Declaration/InterfaceDeclaration.java +++ /dev/null @@ -1,17 +0,0 @@ -package tree.Declaration; - -import tree.Modifiers; - -public class InterfaceDeclaration extends Declaration { - // No structure - - // Creation - public InterfaceDeclaration(Modifiers m, String n) { - super(m, n, null); - - } - - // No report - - // No generation -} diff --git a/src/main/java/tree/Declaration/MethodDeclaration.java b/src/main/java/tree/Declaration/MethodDeclaration.java deleted file mode 100644 index 1366a1b5..00000000 --- a/src/main/java/tree/Declaration/MethodDeclaration.java +++ /dev/null @@ -1,131 +0,0 @@ -package tree.Declaration; - -import tree.Dims; -import tree.Entity; -import tree.Modifiers; -import tree.Statement.Block; -import tree.Type.Type; -import tree.Type.TypeList; -import tree.Type.TypeParameters; - -// MethodDeclaration -// : MethodHeader MethodBody -// ; -// -// MethodHeader -// : TypeParameters Type MethodDeclarator ThrowsOpt -// | TypeParameters AnnotationSeq VOID MethodDeclarator ThrowsOpt -// | TypeParameters UnannotatedType MethodDeclarator ThrowsOpt -// | TypeParameters VOID MethodDeclarator ThrowsOpt -// | UnannotatedType MethodDeclarator ThrowsOpt -// | VOID MethodDeclarator ThrowsOpt -// ; -// -// MethodDeclarator -// : IDENTIFIER LPAREN RPAREN DimsOpt -// | IDENTIFIER LPAREN FormalParameterList RPAREN DimsOpt -// ; -// -// ThrowsOpt -// : // empty -// | THROWS ClassTypeList1 -// ; -public class MethodDeclaration extends Declaration { - // Structure - // public Modifiers modifiers; - public TypeParameters typeParameters; - // public Type type; - // public String name; - // public ReceiverDeclaration receiver; -- this is a special kind of ParameterDeclaration - public ParameterDeclarations parameters; - public Dims dims; - public TypeList exceptions; - public Block methodBody; - - // Creation - public MethodDeclaration(MethodHeader header, Block body) { - super(null, header.declarator.name, header.type); - this.typeParameters = header.typeParameters; - this.parameters = header.declarator.parameters; - this.dims = header.declarator.dims; - this.exceptions = header.throwsClause; - this.methodBody = body; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.parameters != null) { - this.parameters.parent = this; - } - if (this.dims != null) { - this.dims.parent = this; - } - if (this.exceptions != null) { - this.exceptions.parent = this; - } - if (this.methodBody != null) { - this.methodBody.parent = this; - } - } - - public MethodDeclaration(Modifiers mods, - TypeParameters typePars, - Type t, - String n, - ParameterDeclarations pars, - Dims dims, - TypeList excs, - Block body) { - super(mods, n, t); - this.typeParameters = typePars; - this.parameters = pars; - this.dims = dims; - this.exceptions = excs; - this.methodBody = body; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.parameters != null) { - this.parameters.parent = this; - } - if (this.dims != null) { - this.dims.parent = this; - } - if (this.exceptions != null) { - this.exceptions.parent = this; - } - if (this.methodBody != null) { - this.methodBody.parent = this; - } - } - - // Reporting - public void report(int sh) { - this.title("METHOD " + name, sh); - if (modifiers != null) { - modifiers.report(sh + Entity.shift); - } - if (typeParameters != null) { - typeParameters.report(sh + Entity.shift); - } - if (type != null) { - type.report(sh + Entity.shift); - } else { - Entity.doShift(sh + Entity.shift); - System.out.println("TYPE VOID"); - } - // Dimensions! --- - if (parameters != null) { - parameters.report(sh + Entity.shift); - } - if (exceptions != null) { - exceptions.report(sh + Entity.shift); - } - if (methodBody != null) { - title("METHOD BODY", sh + Entity.shift); - methodBody.report(sh + 2 * Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/MethodDeclarator.java b/src/main/java/tree/Declaration/MethodDeclarator.java deleted file mode 100644 index c4740513..00000000 --- a/src/main/java/tree/Declaration/MethodDeclarator.java +++ /dev/null @@ -1,37 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Dims; -import tree.Entity; - -// Intermediate class - won't appear in the AST -// -// MethodDeclarator -// : IDENTIFIER LPAREN RPAREN DimsOpt -// | IDENTIFIER LPAREN FormalParameterList /*FormalParameters*/ RPAREN DimsOpt -// ; -public class MethodDeclarator extends Entity { - // Structure - public String name; - public ParameterDeclarations parameters; - public Dims dims; - - // Creation - public MethodDeclarator(Token token, ParameterDeclarations pars, Dims dims) { - this.name = token.image; - this.parameters = pars; - this.dims = dims; - - if (this.parameters != null) { - this.parameters.parent = this; - } - if (this.dims != null) { - this.dims.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } -} diff --git a/src/main/java/tree/Declaration/MethodHeader.java b/src/main/java/tree/Declaration/MethodHeader.java deleted file mode 100644 index b9fc6a01..00000000 --- a/src/main/java/tree/Declaration/MethodHeader.java +++ /dev/null @@ -1,53 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Type.Type; -import tree.Type.TypeList; -import tree.Type.TypeParameters; - -// The intermediate class - won't appera in the AST -// -// MethodHeader -// : TypeParameters Type MethodDeclarator ThrowsOpt -// | TypeParameters AnnotationSeq VOID MethodDeclarator ThrowsOpt -// | TypeParameters UnannotatedType MethodDeclarator ThrowsOpt -// | TypeParameters VOID MethodDeclarator ThrowsOpt -// | UnannotatedType MethodDeclarator ThrowsOpt -// | VOID MethodDeclarator ThrowsOpt -// ; -public class MethodHeader extends Entity { - // Structure - public TypeParameters typeParameters; - public Type type; // together with annotations? - public MethodDeclarator declarator; - public TypeList throwsClause; - - public MethodHeader( - TypeParameters tpars, - Type type, - MethodDeclarator methodDecl, - TypeList thr) { - this.typeParameters = tpars; - this.type = type; - this.declarator = methodDecl; - this.throwsClause = thr; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.type != null) { - this.type.parent = this; - } - if (this.declarator != null) { - this.declarator.parent = this; - } - if (this.throwsClause != null) { - this.throwsClause.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } -} diff --git a/src/main/java/tree/Declaration/NormalClassDeclaration.java b/src/main/java/tree/Declaration/NormalClassDeclaration.java deleted file mode 100644 index 650d9327..00000000 --- a/src/main/java/tree/Declaration/NormalClassDeclaration.java +++ /dev/null @@ -1,126 +0,0 @@ -package tree.Declaration; - -import java.util.List; -import java.util.stream.Collectors; -import lexer.Token; -import lexer.TokenCode; -import tree.Entity; -import tree.Type.Type; -import tree.Type.TypeList; -import tree.Type.TypeParameters; - -// NormalClassDeclaration -// : /*ModifierSeqOpt*/ CLASS IDENTIFIER -// TypeParametersOpt ClassExtendsOpt ClassImplementsOpt ClassBody -// ; -// -// ClassExtendsOpt -// : // empty -// | EXTENDS Type -// ; -// -// ClassImplementsOpt -// : // empty -// | IMPLEMENTS ClassTypeList1 -// ; -// -// ClassBody -// : LBRACE RBRACE -// | LBRACE ClassBodyDeclarationSeq RBRACE -// ; -// -//ClassBodyDeclarationSeq -// : ClassBodyDeclaration -// | ClassBodyDeclarationSeq ClassBodyDeclaration -// ; -// -//ClassBodyDeclaration -// : ModifierSeqOpt PureBodyDeclaration -// | Block // InstanceInitializer -// | STATIC Block // StaticInitializer -// | SEMICOLON -// ; -public class NormalClassDeclaration extends ClassDeclaration { - // Structure - public TypeParameters typeParameters; - public Type extendedType; - public TypeList interfaces; - public Declarations body; - - // Creation - public NormalClassDeclaration(Token n, - TypeParameters typePars, - Type extType, - TypeList ints, - Declarations body) { - super(null, n.image); - this.typeParameters = typePars; - this.extendedType = extType; - this.interfaces = ints; - this.body = body; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.extendedType != null) { - this.extendedType.parent = this; - } - if (this.interfaces != null) { - this.interfaces.parent = this; - } - if (this.body != null) { - this.body.parent = this; - } - } - - public List getStaticVariables() { - return body.declarations.stream() - .filter(dec -> dec instanceof VariableDeclaration) - .filter(dec -> dec.modifiers.modifiers.modifiers.contains(TokenCode.Static)) - .map(dec -> (VariableDeclaration) dec) - .collect(Collectors.toList()); - } - - public List getNonStaticVariables() { - return body.declarations.stream() - .filter(dec -> dec instanceof VariableDeclaration) - .filter(dec -> !dec.modifiers.modifiers.modifiers.contains(TokenCode.Static)) - .map(dec -> (VariableDeclaration) dec) - .collect(Collectors.toList()); - } - - public List getStaticMethods() { - return body.declarations.stream() - .filter(dec -> dec instanceof MethodDeclaration) - .filter(dec -> dec.modifiers.modifiers.modifiers.contains(TokenCode.Static)) - .map(dec -> (MethodDeclaration) dec) - .collect(Collectors.toList()); - } - - public List getNonStaticMethods() { - return body.declarations.stream() - .filter(dec -> dec instanceof MethodDeclaration) - .filter(dec -> !dec.modifiers.modifiers.modifiers.contains(TokenCode.Static)) - .map(dec -> (MethodDeclaration) dec) - .collect(Collectors.toList()); - } - - // Reporting - public void report(int sh) { - this.title("CLASS DECLARATION " + this.name, sh); - if (this.typeParameters != null) { - this.typeParameters.report(sh + Entity.shift); - } - if (this.extendedType != null) { - this.title("SUPER", sh + Entity.shift); - this.extendedType.report(sh + Entity.shift); - } - if (this.interfaces != null) { - this.interfaces.report(sh + Entity.shift); - } - if (body != null) { - body.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/NormalInterfaceDeclaration.java b/src/main/java/tree/Declaration/NormalInterfaceDeclaration.java deleted file mode 100644 index c726740a..00000000 --- a/src/main/java/tree/Declaration/NormalInterfaceDeclaration.java +++ /dev/null @@ -1,55 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Entity; -import tree.Type.TypeList; -import tree.Type.TypeParameters; - -// NormalInterfaceDeclaration -// : INTERFACE IDENTIFIER TypeParametersOpt InterfaceExtendsOpt InterfaceBody -// ; -public class NormalInterfaceDeclaration extends InterfaceDeclaration { - // Structure - // public String identifier; - public TypeParameters typeParameters; - public TypeList extendingInterfaces; - public Declarations interfaceBody; - - // Creation - public NormalInterfaceDeclaration( - Token id, - TypeParameters typePars, - TypeList extTypes, - Declarations body) { - super(null, id.image); - this.typeParameters = typePars; - this.extendingInterfaces = extTypes; - this.interfaceBody = body; - - if (this.typeParameters != null) { - this.typeParameters.parent = this; - } - if (this.extendingInterfaces != null) { - this.extendingInterfaces.parent = this; - } - if (this.interfaceBody != null) { - this.interfaceBody.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("INTERFACE " + super.name); - if (typeParameters != null) { - typeParameters.report(sh + Entity.shift); - } - if (extendingInterfaces != null) { - extendingInterfaces.report(sh + Entity.shift); - } - if (interfaceBody != null) { - interfaceBody.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/ParameterDeclaration.java b/src/main/java/tree/Declaration/ParameterDeclaration.java deleted file mode 100644 index c3ff510f..00000000 --- a/src/main/java/tree/Declaration/ParameterDeclaration.java +++ /dev/null @@ -1,88 +0,0 @@ -package tree.Declaration; - -import com.sun.source.tree.EmptyStatementTree; -import lexer.Token; -import tree.*; -import tree.Modifiers; -import tree.Type.*; - -// FormalParameter -// : ModifierSeq UnannotatedType FormalParameterTail -// | UnannotatedType FormalParameterTail -// ; -// -// FormalParameterTail -// // Normal formal parameter -// : IDENTIFIER DimsOpt -// | AnnotationSeqOpt ELLIPSIS IDENTIFIER -// -// // ReceiverParameter -// | THIS -// | IDENTIFIER DOT THIS -// ; -public class ParameterDeclaration extends Declaration -{ - // Structure -// public Modifiers modifiers; -// public Type type; -// public String name; - public Annotations ellAnnotations; - public boolean signEllipsis; - public Dims dims; - - // Creation - public ParameterDeclaration(Modifiers mods, - Type t, - String n, - Annotations ellAnns, - boolean signEll, - Dims dims) - { - super(mods,n,t); - this.ellAnnotations = ellAnns; - this.signEllipsis = signEll; - this.dims = dims; - - if ( this.ellAnnotations != null ) this.ellAnnotations.parent = this; - if ( this.dims != null ) this.dims.parent = this; - } - public ParameterDeclaration(Token token) - { - // For the single lambda parameter - this(null,null,token.image,null,false,null); - } - public static ParameterDeclaration create(Modifiers mods,Type type,ParameterTail tail) - { - if ( tail.thisSign ) // this is the receiver declaration - return createReceiver(mods,type,tail.identifier); - else // this is a usual parameter declaration - return createParameter(mods,type,tail.identifier,tail.annotations,tail.ellipsisSign,tail.dims); - } - private static ParameterDeclaration createParameter(Modifiers mods,Type t,String n, - Annotations ellAnns, boolean signEll,Dims dims) - { - return new ParameterDeclaration(mods,t,n,ellAnns,signEll,dims); - } - private static ReceiverDeclaration createReceiver(Modifiers mods,Type t,String n) - { - ReceiverDeclaration receiver = new ReceiverDeclaration(null,t,n); - - receiver.modifiers = mods; - receiver.dims = null; - receiver.ellAnnotations = null; - receiver.signEllipsis = false; - - if ( receiver.modifiers != null ) receiver.modifiers.parent = receiver; - return receiver; - } - - // Reporting - public void report(int sh) - { - title("PARAMETER "+name,sh); - if ( super.modifiers != null ) super.modifiers.report(sh+Entity.shift); - if ( super.type != null ) super.type.report(sh+ Entity.shift); - - } - -} diff --git a/src/main/java/tree/Declaration/ParameterDeclarations.java b/src/main/java/tree/Declaration/ParameterDeclarations.java deleted file mode 100644 index 27c2bf3a..00000000 --- a/src/main/java/tree/Declaration/ParameterDeclarations.java +++ /dev/null @@ -1,41 +0,0 @@ -package tree.Declaration; - -import java.util.ArrayList; -import tree.Entity; - -public class ParameterDeclarations extends Entity { - // Structure - public ArrayList parameters; - - // Creation - public ParameterDeclarations(ParameterDeclaration par) { - this.parameters = new ArrayList<>(); - this.parameters.add(par); - if (par != null) { - par.parent = this; - } - } - - public ParameterDeclarations(ArrayList pars) { - this.parameters = pars; - for (var par : pars) { - par.parent = this; - } - } - - public ParameterDeclarations add(ParameterDeclaration par) { - this.parameters.add(par); - if (par != null) { - par.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (ParameterDeclaration p : parameters) { - p.report(sh); - } - } - -} diff --git a/src/main/java/tree/Declaration/ParameterTail.java b/src/main/java/tree/Declaration/ParameterTail.java deleted file mode 100644 index b19590db..00000000 --- a/src/main/java/tree/Declaration/ParameterTail.java +++ /dev/null @@ -1,45 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Annotations; -import tree.Dims; -import tree.Entity; - -// Intermediate class; won't appear in the AST -// -// FormalParameterTail -// : IDENTIFIER DimsOpt -// | AnnotationSeqOpt ELLIPSIS IDENTIFIER -// | THIS // receiver -// | IDENTIFIER DOT THIS // receiver -// ; -public class ParameterTail extends Entity { - // Structure - public Annotations annotations; - public String identifier; - public Dims dims; - public boolean ellipsisSign; - public boolean thisSign; - - // Creation - public ParameterTail(Annotations anns, Token id, Dims dims, boolean ellSign, boolean thisSign) { - this.annotations = anns; - this.identifier = id.image; - this.dims = dims; - this.ellipsisSign = ellSign; - this.thisSign = thisSign; - - if (this.annotations != null) { - this.annotations.parent = this; - } - if (this.dims != null) { - this.dims.parent = this; - } - } - - // Reporting - public void report(int sh) { - // empty - } - -} diff --git a/src/main/java/tree/Declaration/ReceiverDeclaration.java b/src/main/java/tree/Declaration/ReceiverDeclaration.java deleted file mode 100644 index 47d498d3..00000000 --- a/src/main/java/tree/Declaration/ReceiverDeclaration.java +++ /dev/null @@ -1,47 +0,0 @@ -package tree.Declaration; - -import tree.Annotations; -import tree.Entity; -import tree.Type.Type; - -// FormalParameter -// : ModifierSeq UnannotatedType FormalParameterTail -// | UnannotatedType FormalParameterTail -// ; -// -// FormalParameterTail -// // Normal formal parameter -// : IDENTIFIER DimsOpt -// | AnnotationSeqOpt ELLIPSIS IDENTIFIER -// -// // ReceiverParameter -// | THIS <<<======== -// | IDENTIFIER DOT THIS <<<======== -// ; -public class ReceiverDeclaration extends ParameterDeclaration { - // Structure - public Annotations annotations; - // public Type type; - // public String name; - - // Creation - public ReceiverDeclaration(Annotations anns, Type t, String n) { - super(null, t, n, null, false, null); - this.annotations = anns; - - if (this.annotations != null) { - this.annotations.parent = this; - } - } - - // Reporting - public void report(int sh) { - String n = (name != null) ? name + ".THIS" : "THIS"; - title("RECEIVER " + n, sh); - type.report(sh + Entity.shift); - if (annotations != null) { - annotations.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/RecordComponent.java b/src/main/java/tree/Declaration/RecordComponent.java deleted file mode 100644 index f6b25a2d..00000000 --- a/src/main/java/tree/Declaration/RecordComponent.java +++ /dev/null @@ -1,45 +0,0 @@ -package tree.Declaration; - -import tree.Annotations; -import tree.Modifiers; -import tree.Type.Type; - -// RecordComponentListOpt -// : // empty -// | RecordComponent -// | RecordComponentListOpt COMMA RecordComponent -// ; -// -// RecordComponent -// : AnnotationSeqOpt UnannotatedType IDENTIFIER -// | AnnotationSeqOpt UnannotatedType AnnotationSeqOpt ELLIPSIS IDENTIFIER // VariableArityRecordComponent -// ; -public class RecordComponent extends Declaration { - // Structure - // public Modifiers modifiers; - // public String name; - // public Type type; - public Annotations ellAnnotations; - public boolean signEllipsis; - - // Creation - public RecordComponent(Modifiers mods, - String n, - Type t, - Annotations ellAnns, - boolean ell) { - super(mods, n, t); - this.ellAnnotations = ellAnns; - this.signEllipsis = ell; - - if (this.ellAnnotations != null) { - this.ellAnnotations.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/RecordComponents.java b/src/main/java/tree/Declaration/RecordComponents.java deleted file mode 100644 index aa61c71b..00000000 --- a/src/main/java/tree/Declaration/RecordComponents.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Declaration; - -import java.util.ArrayList; -import tree.Entity; - -public class RecordComponents extends Entity { - //Structure - public ArrayList recordComps; - - // Creation - public RecordComponents(RecordComponent comp) { - this.recordComps = new ArrayList<>(); - this.recordComps.add(comp); - if (comp != null) { - comp.parent = this; - } - } - - public RecordComponents add(RecordComponent comp) { - this.recordComps.add(comp); - if (comp != null) { - comp.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - // Empty - } - -} diff --git a/src/main/java/tree/Declaration/RecordDeclaration.java b/src/main/java/tree/Declaration/RecordDeclaration.java deleted file mode 100644 index 4195f344..00000000 --- a/src/main/java/tree/Declaration/RecordDeclaration.java +++ /dev/null @@ -1,77 +0,0 @@ -package tree.Declaration; - -import tree.Modifiers; -import tree.Type.TypeParameters; - -// RecordDeclaration -// : /*ModifierSeqOpt*/ RECORD IDENTIFIER TypeParametersOpt RecordHeader ClassImplementsOpt RecordBody -// ; -// -// RecordHeader -// : LPAREN RecordComponentListOpt RPAREN -// ; -// -// RecordComponentListOpt -// : // empty -// | RecordComponent -// | RecordComponentListOpt COMMA RecordComponent -// ; -// -// RecordComponent -// : AnnotationSeqOpt UnannotatedType IDENTIFIER -// | AnnotationSeqOpt UnannotatedType AnnotationSeqOpt ELLIPSIS IDENTIFIER // VariableArityRecordComponent -// ; -// -// RecordBody -// : LBRACE RBRACE -// | LBRACE RecordBodyDeclarationSeq RBRACE -// ; -// -// RecordBodyDeclarationSeq -// : RecordBodyDeclaration -// | RecordBodyDeclarationSeq RecordBodyDeclaration -// ; -// -// RecordBodyDeclaration -// : ClassBodyDeclaration -// | ModifierSeqOpt IDENTIFIER ConstructorBody // CompactConstructorDeclaration -// ; -public class RecordDeclaration extends ClassDeclaration { - // Structure - public TypeParameters typeParameters; - public RecordComponents recordComponents; - public Declarations body; - // public CompactConstructor !!!!!!!!!!!!!!!!!!!!!!!! - - // Creation - public RecordDeclaration(String n, - Modifiers mods, - TypeParameters typePars, - RecordComponents recordComps, - Declarations body) { - super(mods, n); - this.modifiers = mods; - this.typeParameters = typePars; - this.recordComponents = recordComps; - this.body = body; - - if (this.modifiers != null) { - this.modifiers.parent = this; - } - if (this.typeParameters != null) { - this.typeParameters.parent = null; - } - if (this.recordComponents != null) { - this.recordComponents.parent = this; - } - if (this.body != null) { - this.body.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Declaration/TypeAndDeclarators.java b/src/main/java/tree/Declaration/TypeAndDeclarators.java deleted file mode 100644 index 04328545..00000000 --- a/src/main/java/tree/Declaration/TypeAndDeclarators.java +++ /dev/null @@ -1,28 +0,0 @@ -package tree.Declaration; - -import tree.Entity; -import tree.Type.Type; - -// Intermediate class - won't appear in the AST - -public class TypeAndDeclarators extends Declaration { - // Structure - // public Type type; -- in the base class - public VariableDeclarators declarators; - - // Creation - public TypeAndDeclarators(Type t, VariableDeclarators vds) { - super(null, null, t); - this.declarators = vds; - if (vds != null) { - vds.parent = this; - } - if (Entity.debug) { - System.out.println("Type with declarator(s) taken"); - } - } - - // Reporting - public void report(int sh) { - } -} diff --git a/src/main/java/tree/Declaration/VariableDeclaration.java b/src/main/java/tree/Declaration/VariableDeclaration.java deleted file mode 100644 index 40e89378..00000000 --- a/src/main/java/tree/Declaration/VariableDeclaration.java +++ /dev/null @@ -1,80 +0,0 @@ -package tree.Declaration; - -import tree.Dims; -import tree.Entity; -import tree.Initializer; -import tree.Modifiers; -import tree.Type.Type; - -// ConstantDeclaration -// : Type VariableDeclaratorList SEMICOLON -// ; -// -// LocalVariableDeclaration -// : UnannotatedType VariableDeclaratorList -// | VAR VariableDeclaratorList -// ; -// -// FieldDeclaration -// : /*ModifierSeqOpt*/ UnannotatedType VariableDeclaratorList SEMICOLON -// ; -// -// VariableDeclaratorList -// : VariableDeclarator -// | VariableDeclaratorList COMMA VariableDeclarator -// ; -// -// VariableDeclarator -// : IDENTIFIER -// | IDENTIFIER EQUAL Expression -// | IDENTIFIER Dims -// | IDENTIFIER Dims EQUAL ArrayInitializer -// ; -public class VariableDeclaration extends Declaration { - // Structure - // public Modifiers modifiers; -- from the base class - // public String name; -- from the base class - public Dims dims; - - // Either a single expression, or a list of initializers - public Initializer initializer; - - // Creation - public VariableDeclaration(String n, - Modifiers mods, - Type t, - Dims dims, - Initializer init) { - super(mods, n, t); - this.dims = dims; - this.initializer = init; - - if (this.dims != null) { - this.dims.parent = this; - } - if (this.initializer != null) { - this.initializer.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("VARIABLE DECLARATION " + name, sh); - if (modifiers != null) { - modifiers.report(sh + Entity.shift); - } - if (type != null) { - type.report(sh + Entity.shift); - } else { - Entity.doShift(sh + Entity.shift); - System.out.println("VAR"); - } - if (dims != null) { - dims.report(sh + Entity.shift); - } - if (initializer != null) { - initializer.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Declaration/VariableDeclarator.java b/src/main/java/tree/Declaration/VariableDeclarator.java deleted file mode 100644 index d50d2532..00000000 --- a/src/main/java/tree/Declaration/VariableDeclarator.java +++ /dev/null @@ -1,45 +0,0 @@ -package tree.Declaration; - -import lexer.Token; -import tree.Dims; -import tree.Entity; -import tree.Initializer; - -// Intermediate class: won't appear in the AST -// -// VariableDeclarator -// : IDENTIFIER -// | IDENTIFIER EQUAL Expression -// | IDENTIFIER Dims -// | IDENTIFIER Dims EQUAL ArrayInitializer -// ; -public class VariableDeclarator extends Entity { - // Structure - public String name; - public Dims dims; - public Initializer initializer; - - // Creation - public VariableDeclarator(Token id, Dims dims, Initializer init) { - this.name = id.image; - this.dims = dims; - this.initializer = init; - - if (this.dims != null) { - this.dims.parent = this; - } - if (this.initializer != null) { - this.initializer.parent = this; - } - - if (Entity.debug) { - System.out.println("Variable declarator with " + id.image + " accepted"); - } - } - - // Reporting - public void report(int sh) { - // Empty - } - -} diff --git a/src/main/java/tree/Declaration/VariableDeclarators.java b/src/main/java/tree/Declaration/VariableDeclarators.java deleted file mode 100644 index e4222f29..00000000 --- a/src/main/java/tree/Declaration/VariableDeclarators.java +++ /dev/null @@ -1,42 +0,0 @@ -package tree.Declaration; - -import java.util.ArrayList; -import tree.Entity; - -// Intermediate class; won't appear in the AST -// -public class VariableDeclarators extends Entity { - // Structure - public ArrayList declarators; - - // Creation - public VariableDeclarators(VariableDeclarator decl) { - this.declarators = new ArrayList<>(); - this.declarators.add(decl); - - if (decl != null) { - decl.parent = this; - } - } - - public VariableDeclarators(ArrayList declarators) { - this.declarators = declarators; - for (var d : declarators) { - d.parent = this; - } - } - - public VariableDeclarators add(VariableDeclarator decl) { - this.declarators.add(decl); - if (decl != null) { - decl.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - // Empty - } - -} diff --git a/src/main/java/tree/Dim.java b/src/main/java/tree/Dim.java deleted file mode 100644 index f6505c21..00000000 --- a/src/main/java/tree/Dim.java +++ /dev/null @@ -1,25 +0,0 @@ -package tree; - -// Dim -// : AnnotationSeq LBRACKET RBRACKET -// | LBRACKET RBRACKET -// ; -public class Dim extends Entity { - // Structure - public Annotations annotations; - - // Creation - public Dim(Annotations anns) { - this.annotations = anns; - if (this.annotations != null) { - this.annotations.parent = this; - } - } - - // Reporting - public void report(int sh) { - annotations.report(sh); - System.out.print("[]"); - } - -} diff --git a/src/main/java/tree/Dims.java b/src/main/java/tree/Dims.java deleted file mode 100644 index 8edf32b6..00000000 --- a/src/main/java/tree/Dims.java +++ /dev/null @@ -1,48 +0,0 @@ -package tree; - -import java.lang.reflect.Array; -import java.util.ArrayList; - -public class Dims extends Entity { - // Structure - public ArrayList dimensions; - - // Creation - public Dims() { - dimensions = new ArrayList<>(); - } - - public Dims(Dim dim) { - this.dimensions = new ArrayList<>(); - this.dimensions.add(dim); - if (dim != null) { - dim.parent = this; - } - } - - public Dims(ArrayList dimensions) { - this.dimensions = dimensions; - for (var dim : dimensions) { - dim.parent = this; - } - } - - public Dims add(Dim dim) { - this.dimensions.add(dim); - if (dim != null) { - dim.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - title("Dimensions: ", sh); - Entity.doShift(sh + Entity.shift); - for (int i = 1; i <= dimensions.size(); i++) { - System.out.print("[]"); - } - System.out.println(); - } - -} diff --git a/src/main/java/tree/Entity.java b/src/main/java/tree/Entity.java deleted file mode 100644 index 5778fd91..00000000 --- a/src/main/java/tree/Entity.java +++ /dev/null @@ -1,66 +0,0 @@ -package tree; - -import lexer.Span; -import lexer.Token; - -// The root class of the whole hierarchy of classes -// representing various Java constructs. - -public class Entity { - public static final int shift = 4; - public static boolean debug = false; - public static boolean syntaxOnly = false; - // All entities created by the program are assigned unique numbers. - private static long count = 0; - // Entity's unique number - public long unique; - // Text coordinates of the entity - public Span span; - - // // Tricks for resolving conflicts - // - // public static boolean inBlock = false; - // public static boolean unAnnotatedTypeTaken = false; - - // Machinery for reporting - // Managing references to parent nodes - public Entity parent; - - // Constructors - public Entity() { - count++; - unique = count; - } - - public Entity(Span span) { - this(); - this.span = span; - } - - public Entity(Token token) { - this(); - this.span = token.span; - } - - public static void doShift(int sh) { - for (int i = 1; i <= sh; i++) { - System.out.print(" "); - } - } - - public void outUnique() { - System.out.print(unique); - System.out.print(":"); - } - - public void title(String n, int sh) { - doShift(sh); - outUnique(); - System.out.println(n); - } - - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Expression/ArgumentList.java b/src/main/java/tree/Expression/ArgumentList.java deleted file mode 100644 index b2868412..00000000 --- a/src/main/java/tree/Expression/ArgumentList.java +++ /dev/null @@ -1,51 +0,0 @@ -package tree.Expression; - -import java.util.ArrayList; -import java.util.Collection; - -import tree.Entity; - -// Arguments -// : LPAREN RPAREN -// | LPAREN ArgumentList RPAREN -// ; -// -// ArgumentList -// : Expression -// | ArgumentList COMMA Expression -// ; -public class ArgumentList extends Entity { - // Structure - public ArrayList arguments; - - // Creation - public ArgumentList(Expression expr) { - this.arguments = new ArrayList<>(); - this.arguments.add(expr); - if (expr != null) { - expr.parent = this; - } - } - - public ArgumentList(Collection exprs) { - this.arguments = new ArrayList<>(); - this.arguments.addAll(exprs); - } - - public ArgumentList add(Expression expr) { - this.arguments.add(expr); - if (expr != null) { - expr.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (Expression arg : arguments) { - arg.report(sh); - // System.out.println(); - } - } - -} diff --git a/src/main/java/tree/Expression/ArrayAccess.java b/src/main/java/tree/Expression/ArrayAccess.java deleted file mode 100644 index 63a140a8..00000000 --- a/src/main/java/tree/Expression/ArrayAccess.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Expression; - -import tree.Entity; - -// ArrayAccess -// : CompoundName LBRACKET Expression RBRACKET -// | Primary LBRACKET Expression RBRACKET -// ; -public class ArrayAccess extends Expression { - // Structure - public Expression expression; - public Expression size; - - // Creation - public ArrayAccess(Expression expr, Expression size) { - this.expression = expr; - this.size = size; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.size != null) { - this.size.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("ARRAY ACCESS"); - expression.report(sh + Entity.shift); - size.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Expression/Binary.java b/src/main/java/tree/Expression/Binary.java deleted file mode 100644 index 79a69b0b..00000000 --- a/src/main/java/tree/Expression/Binary.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Expression; - -import lexer.Token; -import lexer.TokenCode; -import tree.Entity; - -public class Binary extends Expression { - // Structure - public Expression left; - public Expression right; - public TokenCode operator; - - // Creation - public Binary(Expression l, Expression r, Token token) { - super(); - this.left = l; - this.right = r; - this.operator = token.code; - - if (this.left != null) { - this.left.parent = this; - } - if (this.right != null) { - this.right.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("BINARY " + operator.toString(), sh); - left.report(sh + Entity.shift); - right.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Expression/Cast.java b/src/main/java/tree/Expression/Cast.java deleted file mode 100644 index 4811337a..00000000 --- a/src/main/java/tree/Expression/Cast.java +++ /dev/null @@ -1,37 +0,0 @@ -package tree.Expression; - -import tree.Entity; -import tree.Type.TypeList; - -// CastExpression -// : TargetType UnaryExpression -// | TargetType LambdaExpression -// ; -public class Cast extends Expression { - // Structure - public TypeList types; - public Expression expression; - - // Creation - public Cast(TypeList types, Expression expr) { - this.types = types; - this.expression = expr; - - if (this.types != null) { - this.types.parent = this; - } - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("CAST"); - types.title("Target types:", sh + Entity.shift); - types.report(sh + 2 * Entity.shift); - expression.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Expression/Conditional.java b/src/main/java/tree/Expression/Conditional.java deleted file mode 100644 index f8d71c6e..00000000 --- a/src/main/java/tree/Expression/Conditional.java +++ /dev/null @@ -1,46 +0,0 @@ -package tree.Expression; - -import tree.Entity; - -// ConditionalExpression -// : ConditionalOrExpression ConditionalOrTail -// ; -// -// ConditionalOrTail -// : %empty -// | QUESTION Expression COLON ConditionalExpression -// | QUESTION Expression COLON LambdaExpression -// ; -public class Conditional extends Expression { - // Structure - public Expression condition; - public Expression thenPart; - public Expression elsePart; - - // Creation - public Conditional(Expression c, Expression t, Expression e) { - this.condition = c; - this.thenPart = t; - this.elsePart = e; - - if (this.condition != null) { - this.condition.parent = this; - } - if (this.thenPart != null) { - this.thenPart.parent = this; - } - if (this.elsePart != null) { - this.elsePart.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("CONDITIONAL"); - condition.report(sh + Entity.shift); - thenPart.report(sh + Entity.shift); - elsePart.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Expression/Expression.java b/src/main/java/tree/Expression/Expression.java deleted file mode 100644 index fae33bd6..00000000 --- a/src/main/java/tree/Expression/Expression.java +++ /dev/null @@ -1,6 +0,0 @@ -package tree.Expression; - -import tree.Entity; - -public class Expression extends Entity { -} diff --git a/src/main/java/tree/Expression/Expressions.java b/src/main/java/tree/Expression/Expressions.java deleted file mode 100644 index d9290691..00000000 --- a/src/main/java/tree/Expression/Expressions.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Expression; - -import java.util.ArrayList; -import tree.Entity; - -public class Expressions extends Entity { - // Structure - public ArrayList expressions; - - // Creation - public Expressions(Expression expr) { - this.expressions = new ArrayList<>(); - this.expressions.add(expr); - if (expr != null) { - expr.parent = this; - } - } - - public Expressions add(Expression expr) { - this.expressions.add(expr); - if (expr != null) { - expr.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (Expression e : expressions) { - e.report(sh); - System.out.println(); - } - } - -} diff --git a/src/main/java/tree/Expression/FieldAccess.java b/src/main/java/tree/Expression/FieldAccess.java deleted file mode 100644 index 91ff547b..00000000 --- a/src/main/java/tree/Expression/FieldAccess.java +++ /dev/null @@ -1,42 +0,0 @@ -package tree.Expression; - -import lexer.Token; -import tree.Entity; - -// FieldAccess -// : Primary DOT IDENTIFIER -// | SUPER DOT IDENTIFIER -// | CompoundName DOT SUPER DOT IDENTIFIER -// ; -public class FieldAccess extends Expression { - // Structure - public Expression expression; // Primary or SimpleReference - public boolean superSign; - public String identifier; - - // Creation - public FieldAccess(Expression expr, boolean ss, Token id) { - this.expression = expr; - this.superSign = ss; - this.identifier = id.image; - - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - if (expression != null) { - expression.report(0); - if (superSign) { - System.out.print("."); - } - } else if (superSign) { - System.out.print("SUPER."); - } - System.out.print(identifier); - } - -} diff --git a/src/main/java/tree/Expression/InstanceOf.java b/src/main/java/tree/Expression/InstanceOf.java deleted file mode 100644 index 29877608..00000000 --- a/src/main/java/tree/Expression/InstanceOf.java +++ /dev/null @@ -1,57 +0,0 @@ -package tree.Expression; - -import tree.Declaration.Declaration; -import tree.Entity; -import tree.Type.Type; - -// InstanceofExpression -// : RelationalExpression INSTANCEOF Type -// | RelationalExpression INSTANCEOF Pattern -// ; -public class InstanceOf extends Expression { - // Structure - public Expression expression; - // Either type OR declaration - public Type type; - public Declaration declaration; - - // Creation - public InstanceOf(Expression expr, Type type) { - this.expression = expr; - this.type = type; - this.declaration = null; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.type != null) { - this.type.parent = this; - } - } - - public InstanceOf(Expression expr, Declaration decl) { - this.expression = expr; - this.type = null; - this.declaration = decl; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.declaration != null) { - this.declaration.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("INSTANCEOF"); - expression.report(sh + Entity.shift); - if (type != null) { - type.report(sh + Entity.shift); - } else { - declaration.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Expression/Lambda.java b/src/main/java/tree/Expression/Lambda.java deleted file mode 100644 index 2acde10c..00000000 --- a/src/main/java/tree/Expression/Lambda.java +++ /dev/null @@ -1,72 +0,0 @@ -package tree.Expression; - -import tree.Declaration.ParameterDeclarations; -import tree.Statement.Block; - -// LambdaExpression -// : IDENTIFIER ARROW LambdaBody -// | LambdaParameters ARROW LambdaBody -// ; -// -// LambdaParameters -// : LPAREN RPAREN -// | LPAREN LambdaParameterList1 RPAREN -// | LPAREN LambdaParameterList2 RPAREN -// // | IDENTIFIER -// ; -// -// LambdaParameterList1 -// : IDENTIFIER -// | LambdaParameterList1 COMMA IDENTIFIER -// ; -// -// LambdaParameterList2 -// : LambdaParameter -// | LambdaParameterList2 COMMA LambdaParameter -// ; -// -// LambdaParameter -// // : IDENTIFIER -// : ModifierSeqOpt UnannotatedType IDENTIFIER DimsOpt -// | ModifierSeqOpt VAR IDENTIFIER DimsOpt -// | ModifierSeqOpt UnannotatedType AnnotationSeqOpt ELLIPSIS IDENTIFIER // VariableArityParameter -// ; -public class Lambda extends Expression { - // Structure - public ParameterDeclarations parameters; - // One of these two! - public Expression expression; - public Block block; - - // Creation - public Lambda(ParameterDeclarations pars, Expression expr) { - this.parameters = pars; - this.expression = expr; - this.block = null; - - if (this.parameters != null) { - this.parameters.parent = this; - } - if (this.expression != null) { - this.expression.parent = this; - } - } - - public Lambda(ParameterDeclarations pars, Block block) { - this.parameters = pars; - this.block = block; - - if (this.parameters != null) { - this.parameters.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Expression/Primary/ClassLiteral.java b/src/main/java/tree/Expression/Primary/ClassLiteral.java deleted file mode 100644 index b7ed0997..00000000 --- a/src/main/java/tree/Expression/Primary/ClassLiteral.java +++ /dev/null @@ -1,38 +0,0 @@ -package tree.Expression.Primary; - -import tree.Dims; -import tree.Entity; -import tree.Type.Type; - -// Primary -// : ... -// | Type DimsOpt DOT CLASS // ClassLiteral -// | VOID DimsOpt DOT CLASS // ClassLiteral -// | ... -public class ClassLiteral extends Literal { - // Structure - public Type type; // VOID, if type==null - public Dims dims; - - // Creation - public ClassLiteral(Type t, Dims d) { - super(null); - this.type = t; - this.dims = d; - - if (this.type != null) { - this.type.parent = this; - } - if (this.dims != null) { - this.dims.parent = this; - } - } - - // Reporting - public void report(int sh) { - // Stub - Entity.doShift(sh); - System.out.println("CLASS LITERAL"); - } - -} diff --git a/src/main/java/tree/Expression/Primary/InstanceCreation.java b/src/main/java/tree/Expression/Primary/InstanceCreation.java deleted file mode 100644 index cf96384f..00000000 --- a/src/main/java/tree/Expression/Primary/InstanceCreation.java +++ /dev/null @@ -1,28 +0,0 @@ -package tree.Expression.Primary; - -// Primary -// : ... -// | ClassInstanceCreationExpression -// | ... -// -// ClassInstanceCreationExpression -// : UnqualifiedClassInstanceCreationExpression -// | CompoundName DOT UnqualifiedClassInstanceCreationExpression -// | Primary DOT UnqualifiedClassInstanceCreationExpression -// ; -// -// UnqualifiedClassInstanceCreationExpression -// : NEW TypeArgumentsOpt ClassOrInterfaceTypeToInstantiate Arguments ClassBodyOpt -// ; -// -// ClassOrInterfaceTypeToInstantiate -// : AnnotatedCompoundName TypeArgumentsOpt -// | AnnotatedCompoundName DIAMOND -// ; -// -// AnnotatedCompoundName -// : AnnotationSeqOpt /*AnnotationOpt*/ IDENTIFIER -// | AnnotatedCompoundName DOT AnnotationSeqOpt /*AnnotationOpt*/ IDENTIFIER -// ; -public class InstanceCreation extends Primary { -} diff --git a/src/main/java/tree/Expression/Primary/Literal.java b/src/main/java/tree/Expression/Primary/Literal.java deleted file mode 100644 index 48a15539..00000000 --- a/src/main/java/tree/Expression/Primary/Literal.java +++ /dev/null @@ -1,38 +0,0 @@ -package tree.Expression.Primary; - -import lexer.Token; -import lexer.TokenCode; - -// Primary -// : Literal -// | ... -// | NULL -// | ... -// -// Literal -// : INTEGER_LITERAL -// | FLOATING_POINT_LITERAL -// | TRUE // BOOLEAN_LITERAL -// | FALSE // BOOLEAN_LITERAL -// | CHARACTER_LITERAL -// | STRING_LITERAL -//// | TextBlock // ??? -// | NULL // NullLiteral -// ; -public class Literal extends Primary { - // Structure - public TokenCode code; - public Object value; - - // Creation - public Literal(Token token) { - this.code = token.code; - this.value = token.image; //.value; - } - - // Reporting - public void report(int sh) { - title("LITERAL " + value, sh); - } - -} diff --git a/src/main/java/tree/Expression/Primary/MethodInvocation.java b/src/main/java/tree/Expression/Primary/MethodInvocation.java deleted file mode 100644 index 904e20fb..00000000 --- a/src/main/java/tree/Expression/Primary/MethodInvocation.java +++ /dev/null @@ -1,85 +0,0 @@ -package tree.Expression.Primary; - -import lexer.Token; -import tree.CompoundName; -import tree.Entity; -import tree.Expression.ArgumentList; -import tree.Expression.Expression; -import tree.Expression.SimpleReference; -import tree.Type.TypeArguments; - -// MethodInvocation -// : CompoundName Arguments -// | CompoundName DOT TypeArguments IDENTIFIER Arguments -// | Primary DOT TypeArgumentsOpt IDENTIFIER Arguments -// | SUPER DOT TypeArgumentsOpt IDENTIFIER Arguments -// | CompoundName DOT SUPER DOT TypeArgumentsOpt IDENTIFIER Arguments -// ; -public class MethodInvocation extends Primary { - // Structure - public Expression qualifier; // SimpleReference or Primary - public boolean superSign; - public TypeArguments typeArguments; - public String name; // callee; can be null - public ArgumentList arguments; - - // ================================= - // NOTE! - // If qualifier != null, and name == null, then 'qualifier' actually - // contains the method name -- perhaps, the compound name. - // ================================== - - // Creation - public MethodInvocation(Expression q, boolean ss, TypeArguments targs, Token name, ArgumentList args) { - this.qualifier = q; - this.superSign = ss; - this.typeArguments = targs; - if (name != null) { - this.name = name.image; - } - this.arguments = args; - - if (this.qualifier != null) { - this.qualifier.parent = this; - } - if (this.typeArguments != null) { - this.typeArguments.parent = this; - } - if (this.arguments != null) { - this.arguments.parent = this; - } - } - - // Reporting - public void report(int sh) { - String t = "METHOD INVOCATION: "; - if (superSign) { - t += "SUPER "; - } - if (name != null) { - t += name; - title(t, sh); - } else if (qualifier != null && qualifier instanceof SimpleReference) { - CompoundName cn = ((SimpleReference) qualifier).compoundName; - Entity.doShift(sh); - System.out.print(t); - cn.report(0); - System.out.println(); - } - if (name != null && qualifier != null) { - Entity.doShift(sh); - System.out.println("Qualifier:"); - qualifier.report(sh + Entity.shift); - } - if (typeArguments != null) { - Entity.doShift(sh + Entity.shift); - System.out.println("Type arguments:"); - typeArguments.report(sh + 2 * Entity.shift); - } - if (arguments != null) { - arguments.title("Arguments:", sh + Entity.shift); - arguments.report(sh + 2 * Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Expression/Primary/Parenthesized.java b/src/main/java/tree/Expression/Primary/Parenthesized.java deleted file mode 100644 index c2ba5163..00000000 --- a/src/main/java/tree/Expression/Primary/Parenthesized.java +++ /dev/null @@ -1,26 +0,0 @@ -package tree.Expression.Primary; - -import tree.Expression.Expression; - -// Primary -// : ... -// | LPAREN Expression RPAREN -// | ... -public class Parenthesized extends Primary { - // Structure - public Expression expression; - - // Creation - public Parenthesized(Expression expr) { - this.expression = expr; - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - expression.report(sh); - } - -} diff --git a/src/main/java/tree/Expression/Primary/Primary.java b/src/main/java/tree/Expression/Primary/Primary.java deleted file mode 100644 index 10f68aa7..00000000 --- a/src/main/java/tree/Expression/Primary/Primary.java +++ /dev/null @@ -1,20 +0,0 @@ -package tree.Expression.Primary; - -import tree.Expression.Expression; - -// Primary -// : Literal -// | Type DimsOpt DOT CLASS // ClassLiteral -// | VOID DimsOpt DOT CLASS // ClassLiteral -// | THIS -// | Type DOT THIS -// | LPAREN Expression RPAREN -// | ClassInstanceCreationExpression -// | FieldAccess -// | ArrayAccess -// | MethodInvocation -// | MethodReference -// | ArrayCreationExpression -// ; -public class Primary extends Expression { -} diff --git a/src/main/java/tree/Expression/Primary/This.java b/src/main/java/tree/Expression/Primary/This.java deleted file mode 100644 index b5954586..00000000 --- a/src/main/java/tree/Expression/Primary/This.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Expression.Primary; - -import tree.Entity; -import tree.Type.Type; - -// Primary -// : ... -// | THIS -// | Type DOT THIS -// | ... -public class This extends Primary { - // Empty structure - public Type type; // if non-null then "qualified this" - - // Creation - public This(Type t) { - this.type = t; - if (this.type != null) { - this.type.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.println("THIS"); - if (type != null) { - type.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Expression/SimpleReference.java b/src/main/java/tree/Expression/SimpleReference.java deleted file mode 100644 index 28a94e6a..00000000 --- a/src/main/java/tree/Expression/SimpleReference.java +++ /dev/null @@ -1,26 +0,0 @@ -package tree.Expression; - -import tree.CompoundName; -import tree.Entity; - -public class SimpleReference extends Expression { - // Structure - public CompoundName compoundName; - - // Creation - public SimpleReference(CompoundName cn) { - this.compoundName = cn; - if (cn != null) { - cn.parent = this; - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.print(this.unique + ":REFERENCE TO "); - compoundName.report(sh); - System.out.println(); - } - -} diff --git a/src/main/java/tree/Expression/SwitchExpression.java b/src/main/java/tree/Expression/SwitchExpression.java deleted file mode 100644 index 583baa3d..00000000 --- a/src/main/java/tree/Expression/SwitchExpression.java +++ /dev/null @@ -1,31 +0,0 @@ -package tree.Expression; - -import tree.Statement.SwitchBlock; - -// SwitchExpression -// : SWITCH LPAREN Expression RPAREN SwitchBlock -// ; -public class SwitchExpression extends Expression { - // Structure - public Expression expression; - public SwitchBlock switchBlock; - - // Creation - public SwitchExpression(Expression expr, SwitchBlock block) { - this.expression = expr; - this.switchBlock = block; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.switchBlock != null) { - this.switchBlock.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Expression/UnaryPostfix.java b/src/main/java/tree/Expression/UnaryPostfix.java deleted file mode 100644 index 2dd0917b..00000000 --- a/src/main/java/tree/Expression/UnaryPostfix.java +++ /dev/null @@ -1,28 +0,0 @@ -package tree.Expression; - -import lexer.Token; -import lexer.TokenCode; -import tree.Entity; - -public class UnaryPostfix extends Expression { - // Structure - public TokenCode operator; - public Expression operand; - - // Creation - public UnaryPostfix(Token token, Expression op) { - this.operator = token.code; - this.operand = op; - - if (this.operand != null) { - this.operand.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("UNARY POSTFIX " + operator.toString(), sh); - operand.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Expression/UnaryPrefix.java b/src/main/java/tree/Expression/UnaryPrefix.java deleted file mode 100644 index e00be632..00000000 --- a/src/main/java/tree/Expression/UnaryPrefix.java +++ /dev/null @@ -1,28 +0,0 @@ -package tree.Expression; - -import lexer.Token; -import lexer.TokenCode; -import tree.Entity; - -public class UnaryPrefix extends Expression { - // Structure - public TokenCode operator; - public Expression operand; - - // Creation - public UnaryPrefix(Token token, Expression op) { - this.operator = token.code; - this.operand = op; - - if (this.operand != null) { - this.operand.parent = this; - } - } - - // Reporting - public void report(int sh) { - title("UNARY PREFIX " + operator.toString(), sh); - operand.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Initializer.java b/src/main/java/tree/Initializer.java deleted file mode 100644 index c5f63343..00000000 --- a/src/main/java/tree/Initializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree; - -// ArrayInitializer -// : LBRACE VariableInitializerListOpt RBRACE -// | LBRACE VariableInitializerListOpt COMMA RBRACE -// ; -// -// VariableInitializerListOpt -// : // empty -// | VariableInitializerList -// ; -// -// VariableInitializerList -// : VariableInitializer -// | VariableInitializerList COMMA VariableInitializer -// ; -// -// VariableInitializer -// : Expression -// | ArrayInitializer -// ; -public class Initializer extends Entity { - // NO structure - - // NO creation - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/InitializerArray.java b/src/main/java/tree/InitializerArray.java deleted file mode 100644 index d8ac3499..00000000 --- a/src/main/java/tree/InitializerArray.java +++ /dev/null @@ -1,38 +0,0 @@ -package tree; - -import java.util.ArrayList; - -public class InitializerArray extends Initializer { - // Structure - public ArrayList initializers; - - // Creation - public InitializerArray(Initializer init) { - this.initializers = new ArrayList<>(); - this.initializers.add(init); - if (init != null) { - init.parent = this; - } - } - - public InitializerArray(ArrayList initializers) { - this.initializers = initializers; - for (var init : initializers) { - init.parent = this; - } - } - - public InitializerArray add(Initializer init) { - this.initializers.add(init); - if (init != null) { - init.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/InitializerSimple.java b/src/main/java/tree/InitializerSimple.java deleted file mode 100644 index 892bef20..00000000 --- a/src/main/java/tree/InitializerSimple.java +++ /dev/null @@ -1,22 +0,0 @@ -package tree; - -import tree.Expression.Expression; - -public class InitializerSimple extends Initializer { - // Structure - public Expression expression; - - // Creation - public InitializerSimple(Expression expr) { - this.expression = expr; - if (expr != null) { - expr.parent = this; - } - } - - // Reporting - public void report(int sh) { - expression.report(sh); - } - -} diff --git a/src/main/java/tree/Modifiers.java b/src/main/java/tree/Modifiers.java deleted file mode 100644 index ba39409d..00000000 --- a/src/main/java/tree/Modifiers.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree; - -// ModifierSeq -// : StandardModifierSeq -// | AnnotationSeq StandardModifierSeq -// ; -public class Modifiers extends Entity { - // Structure - public Annotations annotations; - public StandardModifiers modifiers; - - // Creation - public Modifiers(Annotations anns, StandardModifiers mods) { - this.annotations = anns; - this.modifiers = mods; - - if (this.annotations != null) { - this.annotations.parent = this; - } - if (this.modifiers != null) { - this.modifiers.parent = this; - } - } - - // Reporting - public void report(int sh) { - if (annotations != null) { - annotations.report(sh); - System.out.println(); - } - modifiers.report(sh); - // System.out.println(); - } - -} diff --git a/src/main/java/tree/ResourceSpecification.java b/src/main/java/tree/ResourceSpecification.java deleted file mode 100644 index d05fd747..00000000 --- a/src/main/java/tree/ResourceSpecification.java +++ /dev/null @@ -1,18 +0,0 @@ -package tree; - -// ResourceSpecification -// : LPAREN ResourceSeq RPAREN -// | LPAREN ResourceSeq SEMICOLON RPAREN -// ; -// -// ResourceSeq -// : Resource -// | ResourceSeq SEMICOLON Resource -// ; -// -// Resource -// : LocalVariableDeclaration -// | FieldAccess // VariableAccess? - doesn't exist in the grammar? -// ; -public class ResourceSpecification extends Entity { -} diff --git a/src/main/java/tree/StandardModifiers.java b/src/main/java/tree/StandardModifiers.java deleted file mode 100644 index fb98820e..00000000 --- a/src/main/java/tree/StandardModifiers.java +++ /dev/null @@ -1,53 +0,0 @@ -package tree; - -import java.util.ArrayList; -import lexer.Token; -import lexer.TokenCode; - -// StandardModifierSeq -// : StandardModifier -// | StandardModifierSeq StandardModifier -// ; -// -// StandardModifier -// // : Annotation -// : DEFAULT -// | FINAL -// | PUBLIC -// | PROTECTED -// | PRIVATE -// | ABSTRACT -// | STATIC -// | STRICTFP -// | SYNCHRONIZED -// | TRANSIENT -// | VOLATILE -// | OPEN // for modules only -// ; -public class StandardModifiers extends Entity { - // Structure - public ArrayList modifiers; - - // Creation - public StandardModifiers(Token token) { - this.modifiers = new ArrayList<>(); - this.modifiers.add(token.code); - } - - public StandardModifiers add(Token token) { - this.modifiers.add(token.code); - return this; - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - for (TokenCode m : this.modifiers) { - System.out.print(m.toString()); - System.out.print(" "); - } - System.out.println(); - } - -} - diff --git a/src/main/java/tree/Statement/Assert.java b/src/main/java/tree/Statement/Assert.java deleted file mode 100644 index 27a2d15f..00000000 --- a/src/main/java/tree/Statement/Assert.java +++ /dev/null @@ -1,46 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// SimpleStatement -// ... -// | ASSERT Expression SEMICOLON // AssertStatement -// | ASSERT Expression COLON Expression SEMICOLON // AssertStatement -// | ... -// ; -public class Assert extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - public Expression expression2; - - // Creation - public Assert(ArrayList ls, Expression expr, Expression expr2) { - super(ls); - this.expression = expr; - this.expression2 = expr2; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.expression2 != null) { - this.expression2.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - title("ASSERT", sh); - expression.report(sh + Entity.shift); - if (expression2 != null) { - System.out.println(); - Entity.doShift(sh); - System.out.println("DIAG"); - expression2.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Statement/Block.java b/src/main/java/tree/Statement/Block.java deleted file mode 100644 index 89452858..00000000 --- a/src/main/java/tree/Statement/Block.java +++ /dev/null @@ -1,42 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; - -// Block -// : LBRACE RBRACE -// | LBRACE BlockStatementSeq RBRACE -// ; -// -// BlockStatementSeq -// : BlockStatement -// | BlockStatementSeq BlockStatement -// ; -// -// BlockStatement -// : ModifierSeqOpt BlockDeclaration -// | Statement -// ; -public class Block extends Statement { - // Structure - // public ArrayList labels; -- from the base class - public BlockStatements block; - - // Creation - public Block(ArrayList ls, BlockStatements block) { - super(ls); - this.block = block; - - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - if (block != null) { - block.report(sh); - } - } - -} diff --git a/src/main/java/tree/Statement/BlockStatement.java b/src/main/java/tree/Statement/BlockStatement.java deleted file mode 100644 index 78e14071..00000000 --- a/src/main/java/tree/Statement/BlockStatement.java +++ /dev/null @@ -1,65 +0,0 @@ -package tree.Statement; - -import tree.Declaration.Declaration; -import tree.Expression.Expression; - -// BlockStatement -// : ModifierSeqOpt BlockDeclaration -// | Statement -// ; -public class BlockStatement extends Statement { - // Structure: either a declaration OR a statement OR an expression - public Declaration declaration; - public Statement statement; - public Expression expression; - - // Creation - public BlockStatement(Declaration d) { - super(null); - this.declaration = d; - this.statement = null; - this.expression = null; - - if (this.declaration != null) { - this.declaration.parent = this; - } - } - - public BlockStatement(Statement stmt) { - super(null); - this.declaration = null; - this.statement = stmt; - this.expression = null; - - if (this.statement != null) { - this.statement.parent = this; - } - } - - public BlockStatement(Expression expr) { - super(null); - this.declaration = null; - this.statement = null; - this.expression = expr; - - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - if (declaration != null) { - declaration.report(sh); - return; - } - if (statement != null) { - statement.report(sh); - return; - } - if (expression != null) { - expression.report(sh); - } - } - -} diff --git a/src/main/java/tree/Statement/BlockStatements.java b/src/main/java/tree/Statement/BlockStatements.java deleted file mode 100644 index ded4ec4b..00000000 --- a/src/main/java/tree/Statement/BlockStatements.java +++ /dev/null @@ -1,60 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Declaration.TypeAndDeclarators; -import tree.Declaration.VariableDeclaration; -import tree.Declaration.VariableDeclarator; -import tree.Entity; - -public class BlockStatements extends Entity { - // Structure - public ArrayList blockStatements; - - // Creation - public BlockStatements(BlockStatement elem) { - this.blockStatements = new ArrayList<>(); - deconstruct(elem); - } - - public BlockStatements(ArrayList blockStatements) { - this.blockStatements = new ArrayList<>(); - for (var s : blockStatements) { - deconstruct(s); - } - } - - public BlockStatements add(BlockStatement elem) { - deconstruct(elem); - return this; - } - - private void deconstruct(BlockStatement stmt) { - if (stmt != null && stmt.declaration != null && stmt.declaration instanceof TypeAndDeclarators) { - TypeAndDeclarators tds = (TypeAndDeclarators) stmt.declaration; - for (VariableDeclarator declarator : tds.declarators.declarators) { - VariableDeclaration variable = new VariableDeclaration( - declarator.name, tds.modifiers, tds.type, declarator.dims, declarator.initializer - ); - this.blockStatements.add(new BlockStatement(variable)); - if (variable != null) { - variable.parent = this; - } - } - } else { - this.blockStatements.add(stmt); - if (stmt != null) { - stmt.parent = this; - } - } - } - - // Reporting - public void report(int sh) { - for (BlockStatement stmt : blockStatements) { - if (stmt != null) { - stmt.report(sh); - } - } - } - -} diff --git a/src/main/java/tree/Statement/Break.java b/src/main/java/tree/Statement/Break.java deleted file mode 100644 index 8a0e32b6..00000000 --- a/src/main/java/tree/Statement/Break.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import lexer.Token; -import tree.Entity; - -// SimpleStatement -// : ... -// | BREAK SEMICOLON // BreakStatement -// | BREAK IDENTIFIER SEMICOLON // BreakStatement -// | ... -// ; -public class Break extends Statement { - // Structure - // public ArrayList labels; - public String label; - - // Creation - public Break(ArrayList ls, Token label) { - super(ls); - this.label = label.image; - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.print("BREAK "); - if (label != null) { - System.out.print(label); - } - System.out.println(); - } - -} diff --git a/src/main/java/tree/Statement/CatchClause.java b/src/main/java/tree/Statement/CatchClause.java deleted file mode 100644 index f6657061..00000000 --- a/src/main/java/tree/Statement/CatchClause.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Statement; - -import tree.Declaration.CatchParameter; -import tree.Entity; - -// CatchClause -// : CATCH LPAREN CatchFormalParameter RPAREN Block -// ; -public class CatchClause extends Entity { - // Structure - public CatchParameter catchParameter; - public Block block; - - // Creation - public CatchClause(CatchParameter catchPar, Block b) { - this.catchParameter = catchPar; - this.block = b; - - if (this.catchParameter != null) { - this.catchParameter.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/CatchClauses.java b/src/main/java/tree/Statement/CatchClauses.java deleted file mode 100644 index 7895c1dd..00000000 --- a/src/main/java/tree/Statement/CatchClauses.java +++ /dev/null @@ -1,41 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -// CatchesOpt -// : %empty -// | Catches -// ; -// -//Catches -// : CatchClause -// | Catches CatchClause -// ; -public class CatchClauses extends Entity { - // Structure - public ArrayList catchClauses; - - // Creation - public CatchClauses(CatchClause clause) { - this.catchClauses = new ArrayList<>(); - this.catchClauses.add(clause); - if (clause != null) { - clause.parent = this; - } - } - - public CatchClauses add(CatchClause clause) { - this.catchClauses.add(clause); - if (clause != null) { - clause.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/Continue.java b/src/main/java/tree/Statement/Continue.java deleted file mode 100644 index db1b553d..00000000 --- a/src/main/java/tree/Statement/Continue.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import lexer.Token; -import tree.Entity; - -// SimpleStatement -// : ... -// | CONTINUE SEMICOLON // ContinueStatement -// | CONTINUE IDENTIFIER SEMICOLON // ContinueStatement -// | ... -// ; -public class Continue extends Statement { - // Structure - // public ArrayList labels; - public String label; - - // Creation - public Continue(ArrayList ls, Token label) { - super(ls); - this.label = label.image; - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.print("CONTINUE "); - if (label != null) { - System.out.print(label); - } - System.out.println(); - } - -} diff --git a/src/main/java/tree/Statement/Do.java b/src/main/java/tree/Statement/Do.java deleted file mode 100644 index 8c54350e..00000000 --- a/src/main/java/tree/Statement/Do.java +++ /dev/null @@ -1,36 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | DO Statement WHILE LPAREN Expression RPAREN SEMICOLON // DoStatement -// | ... -// ; -public class Do extends Statement { - // Structure - // public ArrayList labels; - public Statement statement; - public Expression condition; - - // Creation - public Do(ArrayList ls, Statement stmt, Expression cond) { - super(ls); - this.statement = stmt; - this.condition = cond; - - if (this.statement != null) { - this.statement.parent = this; - } - if (this.condition != null) { - this.condition.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - } - -} diff --git a/src/main/java/tree/Statement/IfThenElse.java b/src/main/java/tree/Statement/IfThenElse.java deleted file mode 100644 index a42ac989..00000000 --- a/src/main/java/tree/Statement/IfThenElse.java +++ /dev/null @@ -1,63 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// Statement -// : ... -// | IfThenElseStatement -// | ... -// ; -// -// IfThenElseStatement -// : IF LPAREN Expression RPAREN Statement ElsePartOpt -// ; -// -// ElsePartOpt -// : // empty -// | ELSE Statement -// ; -public class IfThenElse extends Statement { - // Structure - // public ArrayList labels; - public Expression condition; - public Statement thenPart; - public Statement elsePart; - - // Creation - public IfThenElse(ArrayList ls, Expression c, Statement t, Statement e) { - super(ls); - this.condition = c; - this.thenPart = t; - this.elsePart = e; - - if (this.condition != null) { - this.condition.parent = this; - } - if (this.thenPart != null) { - this.thenPart.parent = this; - } - if (this.elsePart != null) { - this.elsePart.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.println("IF"); - condition.report(sh + Entity.shift); - // System.out.println(); - Entity.doShift(sh); - System.out.println("THEN"); - thenPart.report(sh + Entity.shift); - if (elsePart != null) { - Entity.doShift(sh); - System.out.println("ELSE"); - elsePart.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Statement/Return.java b/src/main/java/tree/Statement/Return.java deleted file mode 100644 index f1f5f712..00000000 --- a/src/main/java/tree/Statement/Return.java +++ /dev/null @@ -1,39 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | RETURN SEMICOLON // ReturnStatement -// | RETURN Expression SEMICOLON // ReturnStatement -// | ... -// ; -public class Return extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - - // Creation - public Return(ArrayList ls, Expression expr) { - super(ls); - this.expression = expr; - - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.print("RETURN"); - if (expression != null) { - System.out.println(); - expression.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Statement/Statement.java b/src/main/java/tree/Statement/Statement.java deleted file mode 100644 index 9e28aaa2..00000000 --- a/src/main/java/tree/Statement/Statement.java +++ /dev/null @@ -1,86 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import lexer.Token; -import tree.Entity; - -// Statement -// : SimpleStatement -// | LabeledStatement -// | IfThenElseStatement -// | WhileStatement -// | ForStatement -// ; -// -// SimpleStatement -// : Block -// | SEMICOLON // EmptyStatement -// | StatementExpression SEMICOLON // ExpressionStatement -// -// | ASSERT Expression SEMICOLON // AssertStatement -// | ASSERT Expression COLON Expression SEMICOLON // AssertStatement -// -// | SWITCH LPAREN Expression RPAREN SwitchBlock // SwitchStatement -// | DO Statement WHILE LPAREN Expression RPAREN SEMICOLON // DoStatement -// -// | BREAK SEMICOLON // BreakStatement -// | BREAK IDENTIFIER SEMICOLON // BreakStatement -// -// | CONTINUE SEMICOLON // ContinueStatement -// | CONTINUE IDENTIFIER SEMICOLON // ContinueStatement -// -// | RETURN SEMICOLON // ReturnStatement -// | RETURN Expression SEMICOLON // ReturnStatement -// -// | SYNCHRONIZED LPAREN Expression RPAREN Block // SynchronizedStatement -// -// | THROW Expression SEMICOLON // ThrowStatement -// | YIELD Expression SEMICOLON // YieldStatement -// -// // TryStatement -// | TRY Block Catches -// | TRY Block Catches Finally -// | TRY Block Finally -// | TRY ResourceSpecification Block CatchesOpt FinallyOpt // TryWithResourcesStatement -// ; -// -// StatementExpression -// : Assignment -// | PreIncrementExpression -// | PreDecrementExpression -// | PostIncrementExpression -// | PostDecrementExpression -// | MethodInvocation -// | ClassInstanceCreationExpression -// ; -public class Statement extends Entity { - // Structure - public ArrayList labels; - - // Creation - public Statement(ArrayList ls) { - this.labels = ls; - } - - public Statement addLabel(Token label) { - if (labels == null) { - labels = new ArrayList<>(); - } - labels.add(label.image); - return this; - } - - // Reporting - public void report(int sh) { - if (labels == null || labels.size() == 0) { - return; - } - - StringBuilder labs = new StringBuilder("LABELS: "); - for (String lab : labels) { - labs.append(lab).append(" "); - } - Entity.doShift(sh); - System.out.println(labs); - } -} diff --git a/src/main/java/tree/Statement/StatementExpression.java b/src/main/java/tree/Statement/StatementExpression.java deleted file mode 100644 index 1da1f4bf..00000000 --- a/src/main/java/tree/Statement/StatementExpression.java +++ /dev/null @@ -1,35 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Expression.Expression; - -// StatementExpression -// : Assignment -// | PreIncrementExpression -// | PreDecrementExpression -// | PostIncrementExpression -// | PostDecrementExpression -// | MethodInvocation -// | ClassInstanceCreationExpression -// ; -public class StatementExpression extends Statement { - // Structure - public Expression expression; - - // Creation - public StatementExpression(ArrayList ls, Expression expr) { - super(ls); - this.expression = expr; - - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); // printing labels, if any - expression.report(sh); - } - -} diff --git a/src/main/java/tree/Statement/StatementExpressions.java b/src/main/java/tree/Statement/StatementExpressions.java deleted file mode 100644 index 87c9e402..00000000 --- a/src/main/java/tree/Statement/StatementExpressions.java +++ /dev/null @@ -1,27 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -public class StatementExpressions extends Entity { - // Structure - public ArrayList expressions; - - // Creation - public StatementExpressions(StatementExpression expr) { - this.expressions = new ArrayList<>(); - this.expressions.add(expr); - - if (expr != null) { - expr.parent = this; - } - } - - public StatementExpressions add(StatementExpression expr) { - this.expressions.add(expr); - if (expr != null) { - expr.parent = this; - } - return this; - } -} diff --git a/src/main/java/tree/Statement/Switch.java b/src/main/java/tree/Statement/Switch.java deleted file mode 100644 index 6d933c52..00000000 --- a/src/main/java/tree/Statement/Switch.java +++ /dev/null @@ -1,96 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | SWITCH LPAREN Expression RPAREN SwitchBlock // SwitchStatement -// | ... -// ; -// -// SwitchBlock -// : LBRACE SwitchRuleSeq RBRACE -// | LBRACE SwitchBlockStatementGroupSeqOpt RBRACE -// | LBRACE SwitchBlockStatementGroupSeqOpt SwitchLabelSeq RBRACE -// ; -// -// SwitchRuleSeq -// : SwitchRule -// | SwitchRuleSeq SwitchRule -// ; -// -// SwitchRule -// : SwitchLabel ARROW Expression SEMICOLON -// | SwitchLabel ARROW Block -// | SwitchLabel ARROW THROW Expression SEMICOLON // ThrowStatement -// ; -// -// SwitchBlockStatementGroupSeqOpt -// : // empty -// | SwitchBlockStatementGroup -// | SwitchBlockStatementGroupSeqOpt SwitchBlockStatementGroup -// ; -// -// SwitchBlockStatementGroup -// : SwitchLabelSeq -// | SwitchLabelSeq BlockStatementSeq -// ; -// -// SwitchLabelSeq -// : SwitchLabel COLON -// | SwitchLabelSeq SwitchLabel COLON -// ; -// -// SwitchLabel -// : CASE CaseExpressionList -// | DEFAULT -// ; -// -// CaseExpressionList -// : AssignmentExpression -// | CaseExpressionList COMMA AssignmentExpression -// ; -public class Switch extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - - // Either "rules" OR "blocks" - public SwitchRules rules; - public SwitchBlocks blocks; - - // Creation - public Switch(ArrayList ls, Expression expr, SwitchRules rs) { - super(ls); - this.expression = expr; - this.rules = rs; - this.blocks = null; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.rules != null) { - this.rules.parent = this; - } - } - - public Switch(ArrayList ls, Expression expr, SwitchBlocks bs, int useless) { - super(ls); - this.expression = expr; - this.blocks = bs; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.blocks != null) { - this.blocks.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - } - -} diff --git a/src/main/java/tree/Statement/SwitchBlock.java b/src/main/java/tree/Statement/SwitchBlock.java deleted file mode 100644 index 24f1fdbd..00000000 --- a/src/main/java/tree/Statement/SwitchBlock.java +++ /dev/null @@ -1,26 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -public class SwitchBlock extends Entity { - // Structure - public ArrayList labels; - public Block block; - - // Creation - public SwitchBlock(ArrayList ls, Block block) { - this.labels = ls; - this.block = block; - - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/SwitchBlocks.java b/src/main/java/tree/Statement/SwitchBlocks.java deleted file mode 100644 index 3482667d..00000000 --- a/src/main/java/tree/Statement/SwitchBlocks.java +++ /dev/null @@ -1,39 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -public class SwitchBlocks extends Entity { - // Structure - public ArrayList blocks; - - // Creation - public SwitchBlocks(SwitchBlock block) { - this.blocks = new ArrayList<>(); - this.blocks.add(block); - if (block != null) { - block.parent = this; - } - } - - public SwitchBlocks(ArrayList blocks) { - this.blocks = blocks; - for (var block : blocks) { - block.parent = this; - } - } - - public SwitchBlocks add(SwitchBlock block) { - this.blocks.add(block); - if (block != null) { - block.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/SwitchLabel.java b/src/main/java/tree/Statement/SwitchLabel.java deleted file mode 100644 index fb509073..00000000 --- a/src/main/java/tree/Statement/SwitchLabel.java +++ /dev/null @@ -1,33 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -public class SwitchLabel extends Entity { - // Structure - public ArrayList cases; - - // Creation - public SwitchLabel(Expression cs) { - this.cases = new ArrayList<>(); - this.cases.add(cs); - if (cs != null) { - cs.parent = this; - } - } - - public SwitchLabel add(Expression cs) { - this.cases.add(cs); - if (cs != null) { - cs.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/SwitchLabels.java b/src/main/java/tree/Statement/SwitchLabels.java deleted file mode 100644 index 536935ca..00000000 --- a/src/main/java/tree/Statement/SwitchLabels.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -public class SwitchLabels extends Entity { - // Structure - public ArrayList labels; - - // Creation - public SwitchLabels(SwitchLabel label) { - this.labels = new ArrayList<>(); - this.labels.add(label); - if (label != null) { - label.parent = this; - } - } - - public SwitchLabels add(SwitchLabel label) { - this.labels.add(label); - if (label != null) { - label.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/SwitchRule.java b/src/main/java/tree/Statement/SwitchRule.java deleted file mode 100644 index 8ed985bb..00000000 --- a/src/main/java/tree/Statement/SwitchRule.java +++ /dev/null @@ -1,87 +0,0 @@ -package tree.Statement; - -import tree.Entity; -import tree.Expression.Expression; - -// SwitchBlock -// : LBRACE SwitchRuleSeq RBRACE -// | ... -// ; -// -// SwitchRuleSeq -// : SwitchRule -// | SwitchRuleSeq SwitchRule -// ; -// -// SwitchRule -// : SwitchLabel ARROW Expression SEMICOLON -// | SwitchLabel ARROW Block -// | SwitchLabel ARROW THROW Expression SEMICOLON // ThrowStatement -// ; -// -// SwitchLabel -// : CASE CaseExpressionList -// | DEFAULT -// ; -// -// CaseExpressionList -// : AssignmentExpression -// | CaseExpressionList COMMA AssignmentExpression -// ; -public class SwitchRule extends Entity { - // ONE of the following values: - public Expression expression; - public Block block; - public Throw throwStatement; - // Structure - SwitchLabel label; - - // Creation: three cases - public SwitchRule(SwitchLabel l, Expression expr) { - this.label = l; - this.expression = expr; - this.block = null; - this.throwStatement = null; - - if (this.label != null) { - this.label.parent = this; - } - if (this.expression != null) { - this.expression.parent = this; - } - } - - public SwitchRule(SwitchLabel l, Block block) { - this.label = l; - this.block = block; - this.throwStatement = null; - - if (this.label != null) { - this.label.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - } - - public SwitchRule(SwitchLabel l, Throw thrwStmt) { - this.label = l; - this.expression = null; - this.block = null; - this.throwStatement = thrwStmt; - - if (this.label != null) { - this.label.parent = this; - } - if (this.throwStatement != null) { - this.throwStatement.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} - diff --git a/src/main/java/tree/Statement/SwitchRules.java b/src/main/java/tree/Statement/SwitchRules.java deleted file mode 100644 index 6254dd75..00000000 --- a/src/main/java/tree/Statement/SwitchRules.java +++ /dev/null @@ -1,32 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; - -public class SwitchRules extends Entity { - // Structure - public ArrayList rules; - - // Creation - public SwitchRules(SwitchRule rule) { - this.rules = new ArrayList<>(); - this.rules.add(rule); - if (rule != null) { - rule.parent = this; - } - } - - public SwitchRules add(SwitchRule rule) { - this.rules.add(rule); - if (rule != null) { - rule.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Statement/Synchronized.java b/src/main/java/tree/Statement/Synchronized.java deleted file mode 100644 index da48cbd9..00000000 --- a/src/main/java/tree/Statement/Synchronized.java +++ /dev/null @@ -1,36 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | SYNCHRONIZED LPAREN Expression RPAREN Block // SynchronizedStatement -// | ... -// ; -public class Synchronized extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - public Block block; - - // Creation - public Synchronized(ArrayList ls, Expression expr, Block block) { - super(ls); - this.expression = expr; - this.block = block; - - if (this.expression != null) { - this.expression.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - } - -} diff --git a/src/main/java/tree/Statement/Throw.java b/src/main/java/tree/Statement/Throw.java deleted file mode 100644 index 7c7ec8d4..00000000 --- a/src/main/java/tree/Statement/Throw.java +++ /dev/null @@ -1,36 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | THROW Expression SEMICOLON // ThrowStatement -// | ... -// ; -public class Throw extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - - // Creation - public Throw(ArrayList ls, Expression expr) { - super(ls); - this.expression = expr; - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.println("THROW"); - if (expression != null) { - expression.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Statement/Try.java b/src/main/java/tree/Statement/Try.java deleted file mode 100644 index 8a1c4b64..00000000 --- a/src/main/java/tree/Statement/Try.java +++ /dev/null @@ -1,57 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.ResourceSpecification; - -// SimpleStatement -// : ... -// | TRY Block Catches -// | TRY Block Catches Finally -// | TRY Block Finally -// | TRY ResourceSpecification Block CatchesOpt FinallyOpt // TryWithResourcesStatement -// ; -// -// Finally -// : FINALLY Block -// ; -public class Try extends Statement { - // Structure - // public ArrayList labels; - public ResourceSpecification resSpec; - public Block block; - public CatchClauses catches; - public Block finallyBlock; - - // Creation - public Try(ArrayList ls, - ResourceSpecification res, - Block b, - CatchClauses cs, - Block finb) { - super(ls); - this.resSpec = res; - this.block = b; - this.catches = cs; - this.finallyBlock = finb; - - if (this.resSpec != null) { - this.resSpec.parent = this; - } - if (this.block != null) { - this.block.parent = this; - } - if (this.catches != null) { - this.catches.parent = this; - } - if (this.finallyBlock != null) { - this.finallyBlock.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - - } - -} diff --git a/src/main/java/tree/Statement/While.java b/src/main/java/tree/Statement/While.java deleted file mode 100644 index aee32905..00000000 --- a/src/main/java/tree/Statement/While.java +++ /dev/null @@ -1,39 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// WhileStatement -// : WHILE LPAREN Expression RPAREN Statement -// ; -public class While extends Statement { - // Structure - // public ArrayList labels; - public Expression condition; - public Statement statement; - - // Creation - public While(ArrayList ls, Expression c, Statement s) { - super(ls); - this.condition = c; - this.statement = s; - - if (this.condition != null) { - this.condition.parent = this; - } - if (this.statement != null) { - this.statement.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.println("WHILE"); - condition.report(sh + Entity.shift); - statement.report(sh + Entity.shift); - } - -} diff --git a/src/main/java/tree/Statement/Yield.java b/src/main/java/tree/Statement/Yield.java deleted file mode 100644 index 5f99008d..00000000 --- a/src/main/java/tree/Statement/Yield.java +++ /dev/null @@ -1,36 +0,0 @@ -package tree.Statement; - -import java.util.ArrayList; -import tree.Entity; -import tree.Expression.Expression; - -// SimpleStatement -// : ... -// | YIELD Expression SEMICOLON // YieldStatement -// | ... -// ; -public class Yield extends Statement { - // Structure - // public ArrayList labels; - public Expression expression; - - // Creation - public Yield(ArrayList ls, Expression expr) { - super(ls); - this.expression = expr; - if (this.expression != null) { - this.expression.parent = this; - } - } - - // Reporting - public void report(int sh) { - super.report(sh); - Entity.doShift(sh); - System.out.println("YIELD"); - if (expression != null) { - expression.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Type/PrimitiveType.java b/src/main/java/tree/Type/PrimitiveType.java deleted file mode 100644 index ff3a5b9e..00000000 --- a/src/main/java/tree/Type/PrimitiveType.java +++ /dev/null @@ -1,44 +0,0 @@ -package tree.Type; - -import lexer.Token; -import lexer.TokenCode; -import tree.Entity; - -// PrimitiveType -// // NumericType -- IntegralType -// : BYTE -// | SHORT -// | INT -// | LONG -// | CHAR -// // NumericType -- FloatingPointType -// | FLOAT -// | DOUBLE -// | BOOLEAN -// ; -public class PrimitiveType extends UnannotatedType { - // Structure - public TokenCode typeCode; - - // Creation - public PrimitiveType(Token token) { - super(null); - this.typeCode = token.code; - - // Entity.unAnnotatedTypeTaken = true; - if (Entity.debug) { - System.out.println("Primitive type accepted"); - } - } - - // Reporting - public void report(int sh) { - title("TYPE " + typeCode.toString(), sh); - if (super.annotations != null) { - super.annotations.report(sh + Entity.shift); - } - if (super.dimensions != null && super.dimensions.dimensions.size() > 0) { - super.dimensions.report(sh + Entity.shift); - } - } -} \ No newline at end of file diff --git a/src/main/java/tree/Type/Type.java b/src/main/java/tree/Type/Type.java deleted file mode 100644 index 8e49ccba..00000000 --- a/src/main/java/tree/Type/Type.java +++ /dev/null @@ -1,40 +0,0 @@ -package tree.Type; - -import tree.Annotations; -import tree.Entity; - -// The root class of the entire hierarchy for Java types. -// -// Type -// : UnannotatedType -// | AnnotationSeq UnannotatedType -// ; -public class Type extends Entity { - // Structure - public Annotations annotations; - - // Creation - public Type(Annotations annSeq) { - this.annotations = annSeq; - if (this.annotations != null) { - this.annotations.parent = this; - } - } - - public Type addAnnotations(Annotations anns) { - this.annotations = anns; - if (this.annotations != null) { - this.annotations.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - if (annotations == null) { - return; - } - annotations.report(sh); - } - -} \ No newline at end of file diff --git a/src/main/java/tree/Type/TypeArgument.java b/src/main/java/tree/Type/TypeArgument.java deleted file mode 100644 index 094521ba..00000000 --- a/src/main/java/tree/Type/TypeArgument.java +++ /dev/null @@ -1,51 +0,0 @@ -package tree.Type; - -import tree.Annotations; -import tree.Entity; - -// TypeArgument -// : Type { $$ = new TypeArgument($1,0,null); } -// | QUESTION { $$ = new TypeArgument(null,1,null); } -// | QUESTION EXTENDS Type { $$ = new TypeArgument($3,1,null); } -// | QUESTION SUPER Type { $$ = new TypeArgument($3,2,null); } -// | AnnotationSeq QUESTION { $$ = new TypeArgument(null,1,$1); } -// | AnnotationSeq QUESTION EXTENDS Type { $$ = new TypeArgument($4,2,$1); } -// | AnnotationSeq QUESTION SUPER Type { $$ = new TypeArgument($4,3,$1); } -// ; -public class TypeArgument extends Entity { - // Structure - public Type type; - public boolean signExtends; - public boolean signSuper; - public Annotations annotations; - - // Creation - public TypeArgument(Type t, int sign, Annotations anns) { - this.type = t; - signExtends = false; - signSuper = false; - switch (sign) { - case 1 -> signExtends = true; - case 2 -> signSuper = true; - default -> { - } - } - this.annotations = anns; - - if (this.type != null) { - this.type.parent = this; - } - if (this.annotations != null) { - this.annotations.parent = this; - } - } - - // Reporting - public void report(int sh) { - if (type != null) { - type.report(sh); - } - // TODO: the rest - } - -} diff --git a/src/main/java/tree/Type/TypeArguments.java b/src/main/java/tree/Type/TypeArguments.java deleted file mode 100644 index 7521cc7f..00000000 --- a/src/main/java/tree/Type/TypeArguments.java +++ /dev/null @@ -1,55 +0,0 @@ -package tree.Type; - -import java.util.ArrayList; -import tree.Entity; - -// TypeArgumentsOpt -// : // empty -// | TypeArguments -// ; -// -// TypeArguments -// : LESS TypeArgumentList GREATER -// ; -// -// TypeArgumentList -// : TypeArgument -// | TypeArgumentList COMMA TypeArgument -// ; -public class TypeArguments extends Entity { - // Structure - public ArrayList arguments; - - // Creation - public TypeArguments(TypeArgument arg) { - this.arguments = new ArrayList<>(); - this.arguments.add(arg); - if (arg != null) { - arg.parent = this; - } - } - - public TypeArguments(ArrayList args) { - this.arguments = args; - for (TypeArgument arg : args) { - arg.parent = this; - } - } - - public TypeArguments add(TypeArgument arg) { - this.arguments.add(arg); - if (arg != null) { - arg.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - title("TYPE ARGUMENTS", sh); - for (TypeArgument arg : arguments) { - arg.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Type/TypeList.java b/src/main/java/tree/Type/TypeList.java deleted file mode 100644 index e0987c26..00000000 --- a/src/main/java/tree/Type/TypeList.java +++ /dev/null @@ -1,51 +0,0 @@ -package tree.Type; - -import java.util.ArrayList; -import java.util.List; - -import tree.Entity; - -// ClassTypeList1 -// : Type -// | ClassTypeList1 COMMA Type -// ; -// -// ClassTypeList2 -// : Type -// | ClassTypeList2 AMPERSAND Type -// ; -public class TypeList extends Entity { - // Structure - public ArrayList types; - - // Creation - public TypeList(Type t) { - this.types = new ArrayList<>(); - this.types.add(t); - if (t != null) { - t.parent = this; - } - } - - public TypeList(ArrayList types) { - this.types = types; - for (Type t : types) { t.parent = this; } - } - - public TypeList add(Type t) { - this.types.add(t); - if (t != null) { - t.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - for (Type t : types) { - t.report(sh); - } - - } - -} diff --git a/src/main/java/tree/Type/TypeName.java b/src/main/java/tree/Type/TypeName.java deleted file mode 100644 index 584820c9..00000000 --- a/src/main/java/tree/Type/TypeName.java +++ /dev/null @@ -1,58 +0,0 @@ -package tree.Type; - -import tree.CompoundName; -import tree.Entity; - -// UnannotatedType -// : ... -// | CompoundName -// | CompoundName TypeArguments -// | ... -// ; -// TypeArguments -// : LESS TypeArgumentList GREATER -// ; -public class TypeName extends UnannotatedType { - // Structure - public CompoundName compoundName; - public TypeArguments typeArguments; - - // Creation - public TypeName(CompoundName cn, TypeArguments targs) { - super(null); - this.compoundName = cn; - this.typeArguments = targs; - - if (this.compoundName != null) { - this.compoundName.parent = this; - } - if (this.typeArguments != null) { - this.typeArguments.parent = this; - } - - // Entity.unAnnotatedTypeTaken = true; - if (Entity.debug) { - System.out.println("Type name accepted"); - } - } - - // Reporting - public void report(int sh) { - Entity.doShift(sh); - System.out.print("TYPE "); - compoundName.report(0); - System.out.println(); - if (super.annotations != null) { - super.annotations.report(sh + Entity.shift); - } - - if (typeArguments != null) { - typeArguments.report(sh + Entity.shift); - } - - if (super.dimensions != null && super.dimensions.dimensions.size() > 0) { - super.dimensions.report(sh + Entity.shift); - } - } - -} \ No newline at end of file diff --git a/src/main/java/tree/Type/TypeParameter.java b/src/main/java/tree/Type/TypeParameter.java deleted file mode 100644 index 2336ce1b..00000000 --- a/src/main/java/tree/Type/TypeParameter.java +++ /dev/null @@ -1,49 +0,0 @@ -package tree.Type; - -import tree.Annotations; -import tree.Entity; - -// TypeParameter -// : AnnotationSeq TypeParameterTail -// | TypeParameterTail -// ; -// -// TypeParameterTail -// : IDENTIFIER -// | IDENTIFIER EXTENDS AnnotationSeqOpt IDENTIFIER -// | IDENTIFIER EXTENDS ClassTypeList2 -// ; -public class TypeParameter extends Entity { - // Structure - public Annotations annotations; - public String name; - - public Annotations extAnnotations; - public String extendingName; - public TypeList extendingTypes; - - // Creation - public TypeParameter(Annotations anns, TypeParameterTail tail) { - this.annotations = anns; - this.name = tail.identifier; - this.extAnnotations = tail.extAnnotations; - this.extendingName = tail.extending; - this.extendingTypes = tail.types; - - if (this.annotations != null) { - this.annotations.parent = this; - } - if (this.extAnnotations != null) { - this.extAnnotations.parent = this; - } - if (this.extendingTypes != null) { - this.extendingTypes.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Type/TypeParameterTail.java b/src/main/java/tree/Type/TypeParameterTail.java deleted file mode 100644 index f27ad727..00000000 --- a/src/main/java/tree/Type/TypeParameterTail.java +++ /dev/null @@ -1,47 +0,0 @@ -package tree.Type; - -import lexer.Token; -import tree.Annotations; -import tree.Entity; - -// TypeParameterTail -// : IDENTIFIER -// | IDENTIFIER EXTENDS AnnotationSeqOpt IDENTIFIER -// | IDENTIFIER EXTENDS ClassTypeList2 -// ; -public class TypeParameterTail extends Entity { - // Structure - public String identifier; - - // Either extending identifier with annotations OR type list - public Annotations extAnnotations; - public String extending; - public TypeList types; - - // Creation - public TypeParameterTail(Token id, Annotations extAnns, Token ext) { - this.identifier = id.image; - this.extAnnotations = extAnns; - this.extending = ext.image; - this.types = null; - - if (this.extAnnotations != null) { - this.extAnnotations.parent = this; - } - } - - public TypeParameterTail(Token id, TypeList types) { - this.identifier = id.image; - this.types = types; - - if (this.types != null) { - this.types.parent = this; - } - } - - // Reporting - public void report(int sh) { - - } - -} diff --git a/src/main/java/tree/Type/TypeParameters.java b/src/main/java/tree/Type/TypeParameters.java deleted file mode 100644 index 8e263be5..00000000 --- a/src/main/java/tree/Type/TypeParameters.java +++ /dev/null @@ -1,45 +0,0 @@ -package tree.Type; - -import java.util.ArrayList; -import tree.Entity; - -public class TypeParameters extends Entity { - // Structure - public ArrayList typeParameters; - - // Creation - public TypeParameters(TypeParameter tpar) { - this.typeParameters = new ArrayList<>(); - this.typeParameters.add(tpar); - if (tpar != null) { - tpar.parent = this; - } - } - - public TypeParameters(ArrayList params) { - this.typeParameters = params; - for (var tpar : params) { - tpar.parent = this; - } - } - - public TypeParameters add(TypeParameter tpar) { - this.typeParameters.add(tpar); - if (tpar != null) { - tpar.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - if (typeParameters.size() == 0) { - return; - } - this.title("TYPE PARAMETERS", sh); - for (TypeParameter tp : typeParameters) { - tp.report(sh + Entity.shift); - } - } - -} diff --git a/src/main/java/tree/Type/UnannotatedType.java b/src/main/java/tree/Type/UnannotatedType.java deleted file mode 100644 index e6a215af..00000000 --- a/src/main/java/tree/Type/UnannotatedType.java +++ /dev/null @@ -1,37 +0,0 @@ -package tree.Type; - -import tree.Annotations; -import tree.Dim; -import tree.Dims; - -// UnannotatedType -// : PrimitiveType -// | CompoundName -// | CompoundName TypeArguments -// | UnannotatedType Dim // ArrayType -// ; -public class UnannotatedType extends Type { - // Structure - public Dims dimensions; - - // Creation - public UnannotatedType(Annotations anns) { - super(anns); - dimensions = new Dims(); - // Empty - } - - public UnannotatedType addDimension(Dim dim) { - this.dimensions.add(dim); - if (dim != null) { - dim.parent = this; - } - return this; - } - - // Reporting - public void report(int sh) { - // empty - } - -} \ No newline at end of file From 06143f4816e6a075896ddc52ba263ec402d7c9fa Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Sat, 7 May 2022 14:29:35 +0300 Subject: [PATCH 14/29] Fix errors introduced by recent commits --- src/main/java/parser/TreeMappings.kt | 272 ++++++++++-------- src/main/java/translator/Classes.kt | 7 +- src/main/java/translator/MethodInvocations.kt | 28 +- test-hadoop.sh | 22 +- 4 files changed, 196 insertions(+), 133 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 46d20dd6..653a8390 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -14,20 +14,20 @@ import tree.Expression.Primary.This import tree.Statement.* import tree.Type.* -fun CompilationUnitContext.toCompilationUnit() : CompilationUnit = +fun CompilationUnitContext.toCompilationUnit(): CompilationUnit = SimpleCompilationUnit( ImportDeclarations(ArrayList(importDeclaration().map { it.toImportDeclaration() })), TopLevelComponents(ArrayList(typeDeclaration().mapNotNull { it.toTopLevelComponent() })) // FIXME: should be no nulls ) -fun TypeDeclarationContext.toTopLevelComponent() : TopLevelComponent? = +fun TypeDeclarationContext.toTopLevelComponent(): TopLevelComponent? = if (classDeclaration() != null) { TopLevelComponent(classDeclaration().toClassDeclaration()) } else { null // throw java.lang.Exception("Cannot translate") // FIXME } -fun ClassDeclarationContext.toClassDeclaration() : ClassDeclaration = +fun ClassDeclarationContext.toClassDeclaration(): ClassDeclaration = NormalClassDeclaration( identifier().toToken(), typeParameters()?.toTypeParameters(), @@ -36,20 +36,20 @@ fun ClassDeclarationContext.toClassDeclaration() : ClassDeclaration = classBody().toDeclarations() ) -fun ClassBodyContext.toDeclarations() : Declarations = +fun ClassBodyContext.toDeclarations(): Declarations = Declarations(ArrayList(this.classBodyDeclaration().map { it.toDeclaration() }.filterNotNull())) -fun ClassBodyDeclarationContext.toDeclaration() : Declaration? = +fun ClassBodyDeclarationContext.toDeclaration(): Declaration? = memberDeclaration()?.toDeclaration(modifier()) ?: block()?.toDeclaration(STATIC()) ?: null -fun MemberDeclarationContext.toDeclaration(modifiers : List?) : Declaration? = +fun MemberDeclarationContext.toDeclaration(modifiers: List?): Declaration? = methodDeclaration()?.toDeclaration() - // FIXME: support other declarations + // FIXME: support other declarations ?: null -fun MethodDeclarationContext.toDeclaration() : Declaration = +fun MethodDeclarationContext.toDeclaration(): Declaration = MethodDeclaration( null /* FIXME */, null /* FIXME */, @@ -61,16 +61,16 @@ fun MethodDeclarationContext.toDeclaration() : Declaration = methodBody().toBlock() /* FIXME */ ) -fun MethodBodyContext.toBlock() : Block = +fun MethodBodyContext.toBlock(): Block = block()?.toBlock() ?: Block(ArrayList(), BlockStatements(ArrayList())) -fun FormalParametersContext.toParameterDeclarations() : ParameterDeclarations? = +fun FormalParametersContext.toParameterDeclarations(): ParameterDeclarations? = formalParameterList()?.toParameterDeclarations() -fun FormalParameterListContext.toParameterDeclarations() : ParameterDeclarations = +fun FormalParameterListContext.toParameterDeclarations(): ParameterDeclarations = ParameterDeclarations(ArrayList(formalParameter().map { it.toParameterDeclaration() })) -fun FormalParameterContext.toParameterDeclaration() : ParameterDeclaration = +fun FormalParameterContext.toParameterDeclaration(): ParameterDeclaration = ParameterDeclaration( null, // FIXME: Modifiers(ArrayList(variableModifier().map { it.toModifier() })), typeType().toType(), @@ -80,85 +80,117 @@ fun FormalParameterContext.toParameterDeclaration() : ParameterDeclaration = null // FIXME ) -fun TypeTypeOrVoidContext.toType() : Type? = typeType()?.toType() +fun TypeTypeOrVoidContext.toType(): Type? = typeType()?.toType() -fun BlockContext.toDeclaration(isStatic : TerminalNode?) : Declaration = +fun BlockContext.toDeclaration(isStatic: TerminalNode?): Declaration = ClassInitializer(this.toBlock(), isStatic != null) -fun BlockContext.toBlock() : Block = - Block(null /* TODO: always null? */, BlockStatements(ArrayList(this.blockStatement().map { it.toBlockStatement() }))) +fun BlockContext.toBlock(): Block = + Block( + null /* TODO: always null? */, + BlockStatements(ArrayList(this.blockStatement().map { it.toBlockStatement() })) + ) -fun Declaration.toBlockStatement() : BlockStatement = BlockStatement(this) -fun Statement.toBlockStatement() : BlockStatement = BlockStatement(this) +fun Declaration.toBlockStatement(): BlockStatement = BlockStatement(this) +fun Statement.toBlockStatement(): BlockStatement = BlockStatement(this) -fun BlockStatementContext.toBlockStatement() : BlockStatement? = +fun BlockStatementContext.toBlockStatement(): BlockStatement? = localVariableDeclaration()?.toDeclaration()?.toBlockStatement() ?: statement()?.toStatement()?.toBlockStatement() ?: localTypeDeclaration()?.toDeclaration()?.toBlockStatement() ?: throw Exception("Unsupported block statement: $this") /* FIXME */ -fun LocalTypeDeclarationContext.toDeclaration() : Declaration = +fun LocalTypeDeclarationContext.toDeclaration(): Declaration = classDeclaration()?.toClassDeclaration() ?: throw Exception() /* FIXME */ -fun StatementContext.toStatement() : Statement = +fun StatementContext.toStatement(): Statement = when (this) { - is StatementWhileContext -> While(null /* FIXME */, + is StatementWhileContext -> While( + null /* FIXME */, parExpression().expression().toExpression(), - statement().toStatement()) - is StatementIfContext -> IfThenElse(null, + statement().toStatement() + ) + is StatementIfContext -> IfThenElse( + null, parExpression().expression().toExpression(), statement(0).toStatement(), - statement(1)?.toStatement()) - is StatementExpressionContext -> StatementExpression(null, - expression().toExpression()) - is StatementAssertContext -> Assert(null, + statement(1)?.toStatement() + ) + is StatementExpressionContext -> StatementExpression( + null, + expression().toExpression() + ) + is StatementAssertContext -> Assert( + null, this.expression(0).toExpression(), - this.expression(1)?.toExpression()) + this.expression(1)?.toExpression() + ) is StatementBreakContext -> Break(null, identifier()?.toToken()) is StatementContinueContext -> Continue(null, identifier()?.toToken()) - is StatementForContext -> StatementExpression(null, SimpleReference(CompoundName("for_loop_placeholder"))) /* FIXME */ - is StatementBlockLabelContext -> StatementExpression(null, SimpleReference(CompoundName("block_label_placeholder"))) /* FIXME */ + is StatementForContext -> StatementExpression( + null, + SimpleReference(CompoundName("for_loop_placeholder")) + ) /* FIXME */ + is StatementBlockLabelContext -> StatementExpression( + null, + SimpleReference(CompoundName("block_label_placeholder")) + ) /* FIXME */ is StatementDoContext -> Do(null, statement().toStatement(), parExpression().expression().toExpression()) is StatementReturnContext -> Return(null, expression()?.toExpression()) - is StatementIdentifierLabelContext -> StatementExpression(null, SimpleReference(CompoundName("identifier_label_placeholder"))) /* FIXME */ - is StatementSemiContext -> StatementExpression(null, SimpleReference(CompoundName("semi_noop_placeholder"))) /* FIXME */ - is StatementSwitchContext -> StatementExpression(null, SimpleReference(CompoundName("switch_statement_placeholder"))) /* FIXME */ + is StatementIdentifierLabelContext -> StatementExpression( + null, + SimpleReference(CompoundName("identifier_label_placeholder")) + ) /* FIXME */ + is StatementSemiContext -> StatementExpression( + null, + SimpleReference(CompoundName("semi_noop_placeholder")) + ) /* FIXME */ + is StatementSwitchContext -> StatementExpression( + null, + SimpleReference(CompoundName("switch_statement_placeholder")) + ) /* FIXME */ is StatementSwitchExpressionContext -> StatementExpression(null, switchExpression().toExpression()) - /* Switch(null, - this.parExpression().expression().toExpression(), - SwitchBlocks(ArrayList(switchBlockStatementGroup().map { it.toSwitchBlock() })), - 0 /* FIXME: switchLabels */ - ) */ - is StatementTryResourceSpecificationContext -> StatementExpression(null, SimpleReference(CompoundName("try_resource_placeholder"))) /* FIXME */ - is StatementTryBlockContext -> StatementExpression(null, SimpleReference(CompoundName("try_block_placeholder"))) /* FIXME */ + /* Switch(null, + this.parExpression().expression().toExpression(), + SwitchBlocks(ArrayList(switchBlockStatementGroup().map { it.toSwitchBlock() })), + 0 /* FIXME: switchLabels */ + ) */ + is StatementTryResourceSpecificationContext -> StatementExpression( + null, + SimpleReference(CompoundName("try_resource_placeholder")) + ) /* FIXME */ + is StatementTryBlockContext -> StatementExpression( + null, + SimpleReference(CompoundName("try_block_placeholder")) + ) /* FIXME */ else -> StatementExpression(null, SimpleReference(CompoundName("statement_placeholder"))) /* FIXME */ // else -> throw Exception("Unsupported statement") /* FIXME */ } -fun SwitchExpressionContext.toExpression() : Expression = +fun SwitchExpressionContext.toExpression(): Expression = SimpleReference(CompoundName("switch_expression_placeholder")) /* FIXME */ - /* FIXME: - SwitchExpression( - parExpression().expression().toExpression(), - ??? - ) */ +/* FIXME: +SwitchExpression( + parExpression().expression().toExpression(), + ??? +) */ -fun SwitchBlockStatementGroupContext.toSwitchBlock() : SwitchBlock = +fun SwitchBlockStatementGroupContext.toSwitchBlock(): SwitchBlock = SwitchBlock( ArrayList(this.switchLabel().map { it.toSwitchLabel() }), null ) -fun SwitchLabelContext.toSwitchLabel() : SwitchLabel = +fun SwitchLabelContext.toSwitchLabel(): SwitchLabel = SwitchLabel( constantExpression?.toExpression() ?: enumConstantName?.toCompoundName()?.toExpression() ?: null ) -fun org.antlr.v4.runtime.Token.toCompoundName() : CompoundName = CompoundName(text) -fun org.antlr.v4.runtime.Token.toToken() : Token = +fun org.antlr.v4.runtime.Token.toCompoundName(): CompoundName = CompoundName(text) +fun org.antlr.v4.runtime.Token.toToken(): Token = when (type) { ADD -> Token(TokenCode.Plus) MUL -> Token(TokenCode.Star) @@ -186,30 +218,28 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = XOR_ASSIGN -> Token(TokenCode.CaretAssign) LSHIFT_ASSIGN -> Token(TokenCode.LeftShiftAssign) DOT -> Token(TokenCode.Dot) + INSTANCEOF -> Token(TokenCode.Instanceof) + QUESTION -> Token(TokenCode.Question) else -> throw Exception("unsupported token: $text ($type)") } -fun CompoundName.toExpression() : Expression = SimpleReference(this) +fun CompoundName.toExpression(): Expression = SimpleReference(this) -fun ExpressionContext.toExpression() : Expression = +fun ExpressionContext.toExpression(): Expression = if (this.bop != null) { val expr0 = - expression(0)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() + expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() val expr1 = - expression(1)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() ?: - methodCall()?.toExpression(expr0) ?: - SimpleReference(CompoundName("expression_placeholder_expr1")) /* FIXME */ + expression(1)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() + ?: methodCall()?.toExpression(expr0) + ?: SimpleReference(CompoundName("expression_placeholder_expr1")) /* FIXME */ if (this.bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 is SimpleReference -> FieldAccess( - expr0, - SUPER() != null, - Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable + expr0, + SUPER() != null, + Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable ) else -> SimpleReference(CompoundName("expression_placeholder_bop_dot")) /* FIXME */ } @@ -223,51 +253,57 @@ fun ExpressionContext.toExpression() : Expression = // SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ // } } else { - expression(0)?.toExpression() ?: - primary()?.toExpression() ?: - identifier()?.toExpression() ?: - methodCall()?.toExpression(null) ?: - SimpleReference(CompoundName("expression_placeholder_not_bop")) /* FIXME */ + expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() + ?: methodCall()?.toExpression(null) + ?: SimpleReference(CompoundName("expression_placeholder_not_bop")) /* FIXME */ } -fun MethodCallContext.toExpression(expr: Expression?) : Expression { +fun MethodCallContext.toExpression(expr: Expression?): Expression { val args = ArgumentList( - expressionList().expression().map { - it.toExpression() - }.toList() + expressionList()?.expression()?.map { + it.toExpression() + }?.toList() ?: listOf() ) return MethodInvocation( - expr, - SUPER() != null, - null, // TODO: type arguments are somewhere else - identifier().toToken(), - args + expr, + SUPER() != null, + null, // TODO: type arguments are somewhere else + identifier().toToken(), + args ) } -fun IdentifierContext.toExpression() : Expression = - SimpleReference(CompoundName(IDENTIFIER().text)) +fun IdentifierContext.toExpression(): Expression = + // TODO: fix this + SimpleReference(CompoundName(IDENTIFIER()?.text ?: "no_identifier")) -fun PrimaryContext.toExpression() : Expression? = - expression()?.toExpression() ?: - identifier()?.toExpression() ?: - THIS()?.let { _ -> This(null) } ?: +fun PrimaryContext.toExpression(): Expression? = + expression()?.toExpression() ?: identifier()?.toExpression() ?: THIS()?.let { _ -> This(null) } ?: /* FIXME: super */ - literal()?.toLiteral() ?: - identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } - /* FIXME: typeOrVoid . CLASS */ - /* FIXME: nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) */ - -fun LiteralContext.toLiteral() : Literal? = - BOOL_LITERAL()?.text?.let { txt -> Literal(Token(if (txt == "true") { TokenCode.True } else { TokenCode.False })) } ?: - integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text))} ?: - NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } ?: - floatLiteral()?.let { x -> Literal(Token(TokenCode.FloatingLiteral, x.text)) } ?: - STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text.drop(1).dropLast(1))) } ?: - Literal(Token(TokenCode.IntegerLiteral, "123456")) ?: /* FIXME: support other literals */ + literal()?.toLiteral() ?: identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } +/* FIXME: typeOrVoid . CLASS */ +/* FIXME: nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) */ + +fun LiteralContext.toLiteral(): Literal? = + BOOL_LITERAL()?.text?.let { txt -> + Literal( + Token( + if (txt == "true") { + TokenCode.True + } else { + TokenCode.False + } + ) + ) + } ?: integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text)) } + ?: NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } + ?: floatLiteral()?.let { x -> Literal(Token(TokenCode.FloatingLiteral, x.text)) } + ?: STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text.drop(1).dropLast(1))) } ?: Literal( + Token(TokenCode.IntegerLiteral, "123456") + ) ?: /* FIXME: support other literals */ throw Exception("unsupported literal $text") /* FIXME */ -fun LocalVariableDeclarationContext.toDeclaration() : Declaration? = +fun LocalVariableDeclarationContext.toDeclaration(): Declaration? = TypeAndDeclarators( typeType()?.toType(), if (identifier() != null) { @@ -277,49 +313,49 @@ fun LocalVariableDeclarationContext.toDeclaration() : Declaration? = } ) -fun IdentifierContext.toVariableDeclarators(expression : ExpressionContext) : VariableDeclarators = +fun IdentifierContext.toVariableDeclarators(expression: ExpressionContext): VariableDeclarators = VariableDeclarators(this.toVariableDeclarator(expression)) -fun IdentifierContext.toVariableDeclarator(expression : ExpressionContext) : VariableDeclarator = +fun IdentifierContext.toVariableDeclarator(expression: ExpressionContext): VariableDeclarator = VariableDeclarator(this.toToken(), null, InitializerSimple(expression.toExpression())) -fun VariableDeclaratorsContext.toVariableDeclarators() : VariableDeclarators = +fun VariableDeclaratorsContext.toVariableDeclarators(): VariableDeclarators = VariableDeclarators(ArrayList(this.variableDeclarator().map { it.toVariableDeclarator() })) -fun VariableDeclaratorContext.toVariableDeclarator() : VariableDeclarator = +fun VariableDeclaratorContext.toVariableDeclarator(): VariableDeclarator = VariableDeclarator( this.variableDeclaratorId().identifier().toToken(), Dims(ArrayList(variableDeclaratorId().LBRACK().size)), this.variableInitializer()?.toInitializer() ) -fun VariableInitializerContext.toInitializer() : Initializer = +fun VariableInitializerContext.toInitializer(): Initializer = arrayInitializer()?.toInitializerArray() ?: InitializerSimple(expression().toExpression()) -fun ArrayInitializerContext.toInitializerArray() : InitializerArray = +fun ArrayInitializerContext.toInitializerArray(): InitializerArray = InitializerArray(ArrayList(variableInitializer().map { it.toInitializer() })) -fun TypeParametersContext.toTypeParameters() : TypeParameters = - TypeParameters(ArrayList(this.typeParameter().map { it.toTypeParameter()})) +fun TypeParametersContext.toTypeParameters(): TypeParameters = + TypeParameters(ArrayList(this.typeParameter().map { it.toTypeParameter() })) -fun TypeParameterContext.toTypeParameter() : TypeParameter = +fun TypeParameterContext.toTypeParameter(): TypeParameter = TypeParameter(null /* FIXME */, TypeParameterTail(this.identifier().toToken(), null /* FIXME */)) -fun TypeListContext.toTypeList() : TypeList = +fun TypeListContext.toTypeList(): TypeList = TypeList(ArrayList(this.typeType().map { it.toType() })) -fun TypeTypeContext.toType() : Type = +fun TypeTypeContext.toType(): Type = when (this) { is TypeClassOrInterfaceTypeContext -> this.toType() is TypePrimitiveTypeContext -> this.toType() else -> throw Exception("not supported") // FIXME: impossible? } -fun TypePrimitiveTypeContext.toType() : Type = +fun TypePrimitiveTypeContext.toType(): Type = primitiveType().toType() // FIXME: annotations and more? -fun TerminalNode.toPrimitiveType() : PrimitiveType? = +fun TerminalNode.toPrimitiveType(): PrimitiveType? = when (this.symbol.type) { BOOLEAN -> PrimitiveType(Token(TokenCode.Boolean)) CHAR -> PrimitiveType(Token(TokenCode.Char)) @@ -331,7 +367,8 @@ fun TerminalNode.toPrimitiveType() : PrimitiveType? = DOUBLE -> PrimitiveType(Token(TokenCode.Double)) else -> throw Exception("Unknown primitive type: " + this.symbol) } -fun PrimitiveTypeContext.toType() : Type = + +fun PrimitiveTypeContext.toType(): Type = BOOLEAN()?.toPrimitiveType() ?: CHAR()?.toPrimitiveType() ?: BYTE()?.toPrimitiveType() @@ -342,22 +379,23 @@ fun PrimitiveTypeContext.toType() : Type = ?: DOUBLE()?.toPrimitiveType() ?: throw Exception("Unsupported primitive type: $this") -fun TypeClassOrInterfaceTypeContext.toType() : Type = +fun TypeClassOrInterfaceTypeContext.toType(): Type = this.classOrInterfaceType().toType() // FIXME -fun ClassOrInterfaceTypeContext.toType() : Type = +fun ClassOrInterfaceTypeContext.toType(): Type = TypeName( CompoundName(this.identifier().map { it.text }), - this.typeArguments().lastOrNull()?.toTypeArguments() // FIXME: we use last() since we do not support types like A.C + this.typeArguments().lastOrNull() + ?.toTypeArguments() // FIXME: we use last() since we do not support types like A.C ) -fun TypeArgumentsContext.toTypeArguments() : TypeArguments = +fun TypeArgumentsContext.toTypeArguments(): TypeArguments = TypeArguments(ArrayList(typeArgument().map { it.toTypeArgument() })) -fun TypeArgumentContext.toTypeArgument() : TypeArgument = +fun TypeArgumentContext.toTypeArgument(): TypeArgument = TypeArgument(typeType()?.toType(), 0 /* FIXME */, null) -fun IdentifierContext.toToken() : Token = Token(TokenCode.Identifier, this.text) +fun IdentifierContext.toToken(): Token = Token(TokenCode.Identifier, this.text) fun QualifiedNameContext.toCompoundName(): CompoundName = CompoundName(identifier().map { it.text }) diff --git a/src/main/java/translator/Classes.kt b/src/main/java/translator/Classes.kt index b63f525e..69c8fa6a 100644 --- a/src/main/java/translator/Classes.kt +++ b/src/main/java/translator/Classes.kt @@ -48,7 +48,12 @@ fun mapClass(clsDec: ClassDeclaration): EOBndExpr { "super".eoDot(), "@" ) - ) + (generateNew(clsDec)) + generateStatic(clsDec) + ) + + (generateNew(clsDec)) + + generateStatic(clsDec) + + clsDec.body.declarations + .filterIsInstance() + .map { mapClass(it) } ), clsDec.name ) diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index 1b35e710..09a93528 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -14,6 +14,7 @@ import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import util.ParseExprTasks import util.isSystemOutCall +import util.logger import java.lang.reflect.Field // TODO: create state object to store binding of expression @@ -28,13 +29,21 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method is FieldAccess -> when (val qualExpr = methodQualifier.expression) { is SimpleReference -> CompoundName( - qualExpr.compoundName.names + listOf(methodQualifier.identifier, methodInvocation.name) + qualExpr.compoundName.names + listOf(methodQualifier.identifier, methodInvocation.name) ).eoDot() - else -> throw IllegalArgumentException("Unsupported yet") + else -> { + logger.warn { "Unsupported field access expression" } + "field_access_expression".eoDot() + } } - else -> - throw IllegalArgumentException("Unsupported method qualifier!") + // TODO: fix this with actual method invocation + is MethodInvocation -> "method_invocation_${methodInvocation.name}".eoDot() + else -> { + logger.warn { "Unsupported method qualifier: ${methodQualifier?.javaClass?.name}" } + "method_qualifier_${methodQualifier?.javaClass?.name}".eoDot() + } } + val callee: EODot = when (val methodQualifier = methodInvocation.qualifier) { is SimpleReference -> if (methodQualifier.compoundName.names.size > 1) @@ -42,8 +51,12 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method else "this".eoDot() is FieldAccess -> methodQualifier.identifier.eoDot() - else -> - throw IllegalArgumentException("Unsupported method qualifier!") + // TODO: fix this with actual method invocation + is MethodInvocation -> "method_invocation_${methodInvocation.name}".eoDot() + else -> { + logger.warn { "Unsupported method qualifier: ${methodQualifier?.javaClass?.name}" } + "method_qualifier_${methodQualifier?.javaClass?.name}".eoDot() + } } return EOObject( @@ -54,7 +67,8 @@ fun mapMethodInvocation(parseExprTasks: ParseExprTasks, methodInvocation: Method EOCopy( src, (if (!isStaticCall) listOf(callee) else ArrayList()) + - (methodInvocation.arguments?.arguments?.map { obj -> parseExprTasks.addTask(obj).eoDot() } ?: listOf()) + (methodInvocation.arguments?.arguments?.map { obj -> parseExprTasks.addTask(obj).eoDot() } + ?: listOf()) ), "@" ) diff --git a/test-hadoop.sh b/test-hadoop.sh index 62af0c91..902e76f3 100755 --- a/test-hadoop.sh +++ b/test-hadoop.sh @@ -7,17 +7,23 @@ echo "Building J2EO..." ./gradlew build -x test jar cp build/libs/J2EO-0.4.0.jar . -echo "Downloading Hadoop..." -# get hadoop from https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz -mkdir ../j2eo-data -wget -O ../j2eo-data/hadoop.tar.gz https://dlcdn.apache.org/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz -# unpack -tar -xf ../j2eo-data/hadoop.tar.gz -C ../j2eo-data +echo "pwd:" $(pwd) + +if [ ! -e "./j2eo-data" ]; then + echo "Downloading Hadoop..." + # get hadoop from https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz + mkdir j2eo-data + wget -O j2eo-data/hadoop.tar.gz https://dlcdn.apache.org/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz + # unpack + tar -xf j2eo-data/hadoop.tar.gz -C j2eo-data +else + echo "Hadoop is already downloaded, skipping download..." +fi echo "Starting J2EO on Hadoop..." # clean old output -rm -rf ../j2eo-data/hadoop-eo +rm -rf j2eo-data/hadoop-eo # as it's not a part of the project # we may want to output to the parent directory -java -jar J2EO-0.4.0.jar -o ../j2eo-data/hadoop-eo ../j2eo-data/hadoop-3.2.3-src +java -jar J2EO-0.4.0.jar -o j2eo-data/hadoop-eo j2eo-data/hadoop-3.2.3-src From 7a54576e5a26d46add798a29fb9e72bc3fd6fb2d Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Tue, 10 May 2022 18:51:01 +0300 Subject: [PATCH 15/29] FEATURE: instance creation --- src/main/java/parser/TreeMappings.kt | 4 +++- src/main/java/translator/Expressions.kt | 19 +++++++++++++++++++ .../translator/preprocessor/Preprocessor.kt | 16 ++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 901ccc38..02c6df2e 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -260,7 +260,9 @@ fun CreatorContext.toExpression() : Expression { fun ArgumentsContext.toArgList() : ArgumentList { return if (expressionList() == null) { - ArgumentList(null) + val args = ArgumentList(null) + args.arguments.removeIf { it == null } + args } else { val argsLst = ArrayList(expressionList().expression().map { it.toExpression() }.toList()) val args = ArgumentList(argsLst.removeFirstOrNull()) diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index f68d574f..6f3a9434 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -3,6 +3,7 @@ package translator import arrow.core.None import eotree.* import lexer.TokenCode +import tree.CompoundName import tree.Expression.Binary import tree.Expression.Expression import tree.Expression.Primary.* @@ -31,10 +32,28 @@ fun mapExpression(parseExprTasks: ParseExprTasks, expr: Expression): EOObject = mapThis(expr) is Parenthesized -> mapParenthesized(parseExprTasks, expr) + is InstanceCreation -> + mapInstanceCreation(parseExprTasks, expr) else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } +fun mapInstanceCreation(parseExprTasks: ParseExprTasks, expr: InstanceCreation): EOObject { + return EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + CompoundName(listOf(expr.ctorType.getTypeName(), "new")).eoDot(), + expr.args.arguments.map { mapExpression(parseExprTasks, it) } + ), + "@" + ) + ) + ) +} + fun mapParenthesized(parseExprTasks: ParseExprTasks, expr: Parenthesized): EOObject = mapExpression(parseExprTasks, expr.expression) diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index afe63202..531bd1af 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -8,6 +8,7 @@ import tree.CompoundName import tree.Declaration.* import tree.Expression.Expression import tree.Expression.Primary.FieldAccess +import tree.Expression.Primary.InstanceCreation import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import tree.InitializerSimple @@ -15,6 +16,7 @@ import tree.Statement.BlockStatement import tree.Statement.Statement import tree.Statement.StatementExpression import tree.Type.PrimitiveType +import tree.Type.Type import tree.Type.TypeName import util.TokenCodes import util.collectPrimitivePackages @@ -227,12 +229,26 @@ private fun preprocessExpr(state: PreprocessorState, expr: Expression) { when (expr) { is SimpleReference -> preprocessSimpleReference(state, expr) is MethodInvocation -> preprocessMethodInvocation(state, expr) + is InstanceCreation -> preprocessInstanceCreation(state, expr) else -> { // this is a generated else block } } } +private fun preprocessInstanceCreation(state: PreprocessorState, instanceCreation: InstanceCreation) { + preprocessType(state, instanceCreation.ctorType) + instanceCreation.args.arguments.forEach { preprocessExpr(state, it) } + instanceCreation.classBody.declarations.forEach { preprocessDecl(state, it) } +} + +private fun preprocessType(state: PreprocessorState, type: Type) { + when (type) { + is TypeName -> preprocessCompoundName(state, type.compoundName) + else -> {} + } +} + private fun preprocessMethodInvocation(state: PreprocessorState, methodInvocation: MethodInvocation) { when (val methodQualifier = methodInvocation.qualifier) { is SimpleReference -> preprocessSimpleReference(state, methodQualifier) From 5c0ab8fdf08bc68c3abeca106cf4adc7534b3931 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Tue, 10 May 2022 19:15:29 +0300 Subject: [PATCH 16/29] FIX: hotfix --- src/main/java/translator/MethodInvocations.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index 26fb7e6a..8c24fa3c 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -13,6 +13,7 @@ import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import util.ParseExprTasks import util.isSystemOutCall +import util.logger import java.lang.reflect.Field // TODO: create state object to store binding of expression From 2a33e751a8c096c816049a7a5586a272844cec7b Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Wed, 11 May 2022 15:15:35 +0300 Subject: [PATCH 17/29] FEATURE: instance creation fixes --- src/main/java/translator/Expressions.kt | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index 60c7c663..957a3208 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -1,6 +1,7 @@ package translator import arrow.core.None +import arrow.core.flatten import eotree.* import lexer.TokenCode import tree.Expression.Binary @@ -56,6 +57,8 @@ fun constructExprName(expr: Expression): String = "t${expr.hashCode()}" is Parenthesized -> "p${expr.hashCode()}" + is InstanceCreation -> + "inst${expr.hashCode()}" else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } @@ -71,8 +74,8 @@ fun mapInstanceCreation(expr: InstanceCreation, name: String): List { EOBndExpr( EOCopy( listOf(expr.ctorType.getTypeName(), "constructor").eoDot(), - listOf(expr.ctorType.getTypeName(), "new").eoDot() - // expr.args.arguments.map { mapExpression() } + listOf(listOf(expr.ctorType.getTypeName(), "new").eoDot()) + + expr.args.arguments.map { constructExprName(it).eoDot() }.toList() ), "@" ) @@ -80,19 +83,7 @@ fun mapInstanceCreation(expr: InstanceCreation, name: String): List { ), name ) - ) - // listOf(), - // None, - // listOf( - // EOBndExpr( - // EOCopy( - // CompoundName(listOf(expr.ctorType.getTypeName(), "new")).eoDot(), - // expr.args.arguments.map { mapExpression(parseExprTasks, it) } - // ), - // "@" - // ) - // ) - // ) + ) + expr.args.arguments.map { mapExpression(it, constructExprName(it)) }.toList().flatten() } fun mapParenthesized(expr: Parenthesized, name: String): List = From 390f78657b89c85e27e94a3a015c29f29f530455 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Thu, 12 May 2022 15:16:51 +0300 Subject: [PATCH 18/29] README: examples added --- README.md | 268 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 268 insertions(+) diff --git a/README.md b/README.md index 64a86c70..02bf6b5f 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,8 @@ bugs in our code. It is also much easier to work with abstraction layer than wit - Then, for each file, translator converts Java AST to EO AST. - Then, EO AST is printed out as a source code to output directory in the same directory structure. +--- + ## Troubleshooting ### Java @@ -119,3 +121,269 @@ Make sure you have these in sync (*mentioning* (not pointing to) the same `jdk` - `echo $JAVA_HOME` - See how to set `$JAVA_HOME` ([link](https://stackoverflow.com/a/18972665)) - If it still points to a wrong directory, see where you might have set it ([link](https://unix.stackexchange.com/a/154957)) and edit that place + +--- + +## Principles of Java to EOLang translation +### Implemented: +- [Class declarations](#class-declarations) +- [Method declarations](#method-declarations) +- [Method invocations](#method-invocations) +- [Local variable declarations](#local-variable-declarations) +- [Field access (via dot-notation)](#field-access) +- [Expressions](#expressions) +- [Instance creation](#instance-creation) + +
+ +#### Class declarations +```java +public class Main { } +``` +translates to +```java ++alias stdlib.lang.class__Object + +[] > class__Main + class__Object > super + super > @ + [] > new + [] > this + class__Object.new > super + super > @ + seq > @ + this +``` +
+ +#### Method declarations +```java +public class Main { + public static void main(String[] args) { } +} +``` +translates to +```java +... +# main :: String -> void +[this args] > main + seq > @ + 0 +... +``` +
+ +#### Method invocations +```java +public class Main { + public static void main(String[] args) { + method(1.0f, new Object()); + } + int method (float a, Object b) { + return a; + } +} +``` +translates to +```java ++alias stdlib.primitives.prim__float ++alias prim__int ++alias stdlib.lang.class__Object + +[] > class__Main + class__Object > super + super > @ + [] > new + [] > this + class__Object.new > super + super > @ + # main :: String -> void + [this args] > main + seq > @ + s206835546 + [] > s206835546 + method > @ + l758013696 + inst1473611564 + [] > l758013696 + prim__float.constructor_2 > @ + prim__float.new + 1.0 + [] > inst1473611564 + Object.constructor > @ + Object.new + # method :: float -> Object -> int + [this a b] > method + seq > @ + s558187323 + [] > s558187323 + s_r680576081 > @ + [] > s_r680576081 + a > @ + seq > @ + this +``` +
+ +#### Local variable declarations +```java +public class Main { + public static void main(String[] args) { + int local = 5; + } +} +``` +translates to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d912011468 + prim__int.constructor_1 > local + prim__int.new + [] > d912011468 + local.write > @ + i_s1048027629 + [] > i_s1048027629 + l599491651 > @ + [] > l599491651 + prim__int.constructor_2 > @ + prim__int.new + 5 +... +``` +
+ +#### Field access +```java +public class Main { + public static void main(String[] args) { + new SomeClass().localVar.otherVar; + } +} +``` +translates to +```java +... +# main :: String -> void +[this args] > main + seq > @ + s756185697 + [] > s756185697 + f_a1308109015.otherVar > @ + [] > f_a1308109015 + inst300031246.localVar > @ + [] > inst300031246 + SomeClass.constructor > @ + SomeClass.new +... +``` +
+ +#### Expressions +```java +public class Main { + public static void main(String[] args) { + int a = 1; + int expr = 1 + 2.0f * 3 - (--a) / 3.0; + } +} +``` +translates to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d148912029 + d604125138 + prim__int.constructor_1 > a + prim__int.new + [] > d148912029 + a.write > @ + i_s521960438 + [] > i_s521960438 + l726950788 > @ + [] > l726950788 + prim__int.constructor_2 > @ + prim__int.new + 1 + prim__int.constructor_1 > expr + prim__int.new + [] > d604125138 + expr.write > @ + i_s631659383 + [] > i_s631659383 + b720167805 > @ + [] > b720167805 + b1466073198.sub > @ + b398690014 + [] > b1466073198 + l1526298704.add > @ + b1593180232 + [] > l1526298704 + prim__int.constructor_2 > @ + prim__int.new + 1 + [] > b1593180232 + l492079624.mul > @ + l380242442 + [] > l492079624 + prim__float.constructor_2 > @ + prim__float.new + 2.0 + [] > l380242442 + prim__int.constructor_2 > @ + prim__int.new + 3 + [] > b398690014 + p1077199500.div > @ + l240166646 + [] > p1077199500 + s_r351028485 > @ + [] > s_r351028485 + a > @ + [] > l240166646 + prim__float.constructor_2 > @ + prim__float.new + 3.0 +... +``` +
+ +#### Instance creation +```java +public class Main { + public static void main(String[] args) { + new SomeClass(param1, "string", new Object()); + } +} +``` +translates to +```java +... +# main :: String -> void +[this args] > main + seq > @ + s599491651 + [] > s599491651 + class__SomeClass.constructor > @ + class__SomeClass.new + s_r1161667116 + l1898220577 + inst1143371233 + [] > s_r1161667116 + param1 > @ + [] > l1898220577 + class__String.constructor_2 > @ + class__String.new + "string" + [] > inst1143371233 + class__Object.constructor > @ + class__Object.new +... +``` +
+ + From faff1f6d77ddedc9a39ffe48f2669feea89077d8 Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Sun, 15 May 2022 11:56:18 +0300 Subject: [PATCH 19/29] Fixed build errors on Java 15 --- src/main/java/parser/TreeMappings.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 49797892..35cd4002 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -305,11 +305,11 @@ fun ArgumentsContext.toArgList() : ArgumentList { fun MethodCallContext.toExpression(expr: Expression?) : Expression { val exprLst = if (expressionList() == null) - ArrayList(listOf()) + listOf() else - ArrayList(expressionList().expression().stream().map { it.toExpression() }.toList()) - val argList = ArgumentList(exprLst.removeFirstOrNull()) - exprLst.forEach { argList.add(it) } + expressionList().expression().map { it.toExpression() }.toList() + val argList = ArgumentList(exprLst.firstOrNull()) + exprLst.drop(1).forEach { argList.add(it) } argList.arguments.removeIf { it == null } return MethodInvocation( expr, From 251eb612a5148e837532f1d6bc7811d3b9535212 Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Sun, 15 May 2022 14:01:34 +0300 Subject: [PATCH 20/29] Added a little more documentation --- src/main/java/translator/Declarations.kt | 13 ++-- src/main/java/translator/Expressions.kt | 9 +++ src/main/java/translator/Initializers.kt | 2 - src/main/java/translator/Literals.kt | 37 +++++++-- src/main/java/translator/MethodInvocations.kt | 2 - src/main/java/translator/Methods.kt | 9 --- src/main/java/translator/Statements.kt | 75 ++++++++++++------- src/main/java/util/Comments.kt | 3 + src/main/java/util/Logging.kt | 2 +- src/main/java/util/ParseExprTasks.kt | 33 -------- src/main/java/util/StaticGenerator.kt | 15 ++-- 11 files changed, 109 insertions(+), 91 deletions(-) delete mode 100644 src/main/java/util/ParseExprTasks.kt diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index 7dfe4ed1..19573492 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -1,8 +1,6 @@ package translator import arrow.core.None -import arrow.core.Option -import arrow.core.some import eotree.* import lexer.TokenCode import tree.Declaration.ClassDeclaration @@ -13,12 +11,14 @@ import tree.Declaration.VariableDeclaration import tree.Initializer import tree.Type.PrimitiveType import tree.Type.TypeName -import util.ParseExprTasks import util.TokenCodes +import util.logger +/** + * Maps a declaration that resides inside of class. + * The name may be confusing, but this DOES NOT map the class declaration itself. + */ fun mapClassDeclaration(dec: Declaration): List { - // TODO: get rid of option and implement all cases - return when (dec) { is MethodDeclaration -> { listOf(mapMethodDeclaration(dec)) @@ -27,9 +27,11 @@ fun mapClassDeclaration(dec: Declaration): List { listOf(mapClass(dec as ClassDeclaration)) } is VariableDeclaration -> { + // FIXME: why do we have static name "n" here? mapVariableDeclaration(dec, "n") } else -> { + logger.warn { "Skipping unsupported class declaration: ${dec.javaClass.name}" } listOf() } } @@ -47,6 +49,7 @@ fun mapDeclaration(dec: Declaration, name: String): List { mapVariableDeclaration(dec, name) } else -> { + logger.warn { "Skipping unsupported declaration: ${dec.javaClass.name}" } listOf() } } diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index 957a3208..e8b708a9 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -64,6 +64,15 @@ fun constructExprName(expr: Expression): String = } +/** + * Maps Java instance creation using "new" operator to EO binding. + * The output has the following structure: + * + * [] > name + * class.constructor_1 > @ + * class.new + * "value" + */ fun mapInstanceCreation(expr: InstanceCreation, name: String): List { return listOf( EOBndExpr( diff --git a/src/main/java/translator/Initializers.kt b/src/main/java/translator/Initializers.kt index a10df030..5ac4d3a6 100644 --- a/src/main/java/translator/Initializers.kt +++ b/src/main/java/translator/Initializers.kt @@ -4,12 +4,10 @@ import arrow.core.None import eotree.EOBndExpr import eotree.EOCopy import eotree.EOObject -import eotree.eoDot import tree.CompoundName import tree.Expression.SimpleReference import tree.Initializer import tree.InitializerSimple -import util.ParseExprTasks fun mapInitializer(initializer: Initializer, name: String): List { return when (initializer) { diff --git a/src/main/java/translator/Literals.kt b/src/main/java/translator/Literals.kt index 85b251fc..13e35c8a 100644 --- a/src/main/java/translator/Literals.kt +++ b/src/main/java/translator/Literals.kt @@ -8,7 +8,17 @@ import lexer.TokenCode import tree.Expression.Primary.Literal import tree.Type.PrimitiveType import util.TokenCodes +import util.logger +/** + * Maps Java literal to J2EO stdlib literal initialization binding. + * Example of output for literal "2" assigned to variable "var": + * + * [] > var + * prim__int.constructor_2 > @ + * prim__int.new + * 2 + */ fun mapLiteral(literal: Literal, name: String): EOBndExpr = when (literal.code) { TokenCode.StringLiteral -> generateEOData( @@ -26,7 +36,12 @@ fun mapLiteral(literal: Literal, name: String): EOBndExpr = TokenCode.IntegerLiteral -> generateEOData( listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), - EOIntData(try {(literal.value as String).toInt()} catch (e: NumberFormatException) { 0 /* FIXME: parse integer literals */ }), + EOIntData(try { + (literal.value as String).toInt() + } catch (e: NumberFormatException) { + logger.warn { "Integer literal parsing is not implemented; falling back to 0" } + 0 /* FIXME: parse integer literals */ + }), name ) TokenCode.True -> generateEOData( @@ -41,16 +56,22 @@ fun mapLiteral(literal: Literal, name: String): EOBndExpr = EOBoolData(false), name ) - TokenCode.Null -> generateEOData( /* FIXME: use proper null */ - listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), - listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), - EOIntData(0), - name - ) + TokenCode.Null -> { + logger.warn { "null value is not supported yet; falling back to 0" } + generateEOData( /* FIXME: use proper null */ + listOf(TokenCodes.PRIM__INT.value, "constructor_2").eoDot(), + listOf(TokenCodes.PRIM__INT.value, "new").eoDot(), + EOIntData(0), + name + ) + } else -> throw IllegalArgumentException("Mapping of type ${literal.javaClass.simpleName} (${literal.code}) is not supported.") } -fun generateEOData(primitiveTypeCall: EODot, primitiveNewCall: EODot, value: EOData, name: String) : EOBndExpr = +/** + * Creates EOObject binding for given primitive type, constructor and value. + */ +private fun generateEOData(primitiveTypeCall: EODot, primitiveNewCall: EODot, value: EOData, name: String): EOBndExpr = EOBndExpr( EOObject( listOf(), diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index ddc49a48..9c55e972 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -11,9 +11,7 @@ import tree.CompoundName import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference -import util.ParseExprTasks import util.isSystemOutCall -import java.lang.reflect.Field // TODO: create state object to store binding of expression fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List { diff --git a/src/main/java/translator/Methods.kt b/src/main/java/translator/Methods.kt index 49dde7e3..51a83ee9 100644 --- a/src/main/java/translator/Methods.kt +++ b/src/main/java/translator/Methods.kt @@ -4,17 +4,9 @@ import arrow.core.* import eotree.EOBndExpr import eotree.EOCopy import eotree.EOObject -import eotree.eoDot import lexer.TokenCode import tree.Declaration.MethodDeclaration import tree.Declaration.ParameterDeclaration -import tree.Declaration.VariableDeclaration -import tree.Entity -import tree.Expression.Expression -import tree.Initializer -import tree.Statement.BlockStatements -import util.ParseExprTasks -import kotlin.collections.flatten // fun MethodDeclaration.getLocalVariables(): List = // // TODO: add support for nested block variables as well @@ -26,7 +18,6 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { val isStatic = dec.modifiers != null && dec.modifiers.modifiers.modifiers.find { it == TokenCode.Static } != null val additionalParameters = if (!isStatic) listOf("this") else ArrayList() - val parseExprTasks = ParseExprTasks() val obj = EOObject( // Non-vararg parameters diff --git a/src/main/java/translator/Statements.kt b/src/main/java/translator/Statements.kt index 05a12750..5715aa82 100644 --- a/src/main/java/translator/Statements.kt +++ b/src/main/java/translator/Statements.kt @@ -1,10 +1,8 @@ package translator import arrow.core.None -import arrow.core.Option import eotree.* import tree.Statement.* -import util.ParseExprTasks import java.util.Random // fun mapBlockStatement(stmt: BlockStatement): EOExpr = @@ -31,10 +29,10 @@ fun mapStatement(statement: Statement, name: String): List = // is Switch -> mapSwitchStatement(parseExprTasks, statement) else -> listOf() // FIXME - // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") + // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") } -fun mapEmptyStmt(name: String) : EOBndExpr = +fun mapEmptyStmt(name: String): EOBndExpr = EOBndExpr( EOObject( listOf(), @@ -70,6 +68,13 @@ fun mapStatementExpression(stmtExpr: StatementExpression, name: String): List @ + * + * returnExpr is mapped into separate object. + */ fun mapReturnStatement(rn: Return, name: String): List { return if (rn.expression != null) { listOf( @@ -94,6 +99,15 @@ fun mapReturnStatement(rn: Return, name: String): List { } } +/** + * Outputs structure of form: + * + * conditionExpr.if > @ + * thenPart + * elsePart + * + * conditionExpr, thenPart and elsePart are mapped into separate objects. + */ fun mapIfThenElseStatement(rn: IfThenElse, name: String): List { val emptyName = "empty${Random().nextInt(Int.MAX_VALUE)}" @@ -121,14 +135,25 @@ fun mapIfThenElseStatement(rn: IfThenElse, name: String): List { ) ) + mapExpression(rn.condition, constructExprName(rn.condition)) + mapStatement(rn.thenPart, constructStmtName(rn.thenPart)) + - if (rn.elsePart != null) { - mapStatement(rn.elsePart, constructStmtName(rn.elsePart)) - } else { - listOf(mapEmptyStmt(emptyName)) - } + if (rn.elsePart != null) { + mapStatement(rn.elsePart, constructStmtName(rn.elsePart)) + } else { + listOf(mapEmptyStmt(emptyName)) + } } -fun mapWhileStatement(rn: While, name: String): List { +/** + * Outputs structure of form: + * + * conditionExpr.while > @ + * [while_i] + * statement + * + * conditionExpr and statement are mapped into separate objects. + * + * TODO: check if we can use iterator inside of statement. + */ +fun mapWhileStatement(wh: While, name: String): List { val emptyName = "empty${Random().nextInt(Int.MAX_VALUE)}" return listOf( @@ -139,14 +164,14 @@ fun mapWhileStatement(rn: While, name: String): List { listOf( EOBndExpr( EOCopy( - listOf(constructExprName(rn.condition), "while").eoDot(), + listOf(constructExprName(wh.condition), "while").eoDot(), EOObject( listOf("while_i"), None, listOf( EOBndExpr( - if (rn.statement != null) { - constructStmtName(rn.statement).eoDot() + if (wh.statement != null) { + constructStmtName(wh.statement).eoDot() } else { emptyName.eoDot() }, @@ -161,15 +186,15 @@ fun mapWhileStatement(rn: While, name: String): List { ), name ) - ) + mapExpression(rn.condition, constructExprName(rn.condition)) + - if (rn.statement != null) { - mapStatement(rn.statement, constructStmtName(rn.statement)) - } else { - listOf(mapEmptyStmt(emptyName)) - } + ) + mapExpression(wh.condition, constructExprName(wh.condition)) + + if (wh.statement != null) { + mapStatement(wh.statement, constructStmtName(wh.statement)) + } else { + listOf(mapEmptyStmt(emptyName)) + } } -fun mapDoStatement(rn: Do, name: String): List { +fun mapDoStatement(rn: Do, name: String): List { val emptyName = "empty${Random().nextInt()}" return listOf( @@ -203,11 +228,11 @@ fun mapDoStatement(rn: Do, name: String): List { name ) ) + mapExpression(rn.condition, constructExprName(rn.condition)) + - if (rn.statement != null) { - mapStatement(rn.statement,constructStmtName(rn.statement)) - } else { - listOf(mapEmptyStmt(emptyName)) - } + if (rn.statement != null) { + mapStatement(rn.statement, constructStmtName(rn.statement)) + } else { + listOf(mapEmptyStmt(emptyName)) + } } // fun mapIfThenElse(statement: IfThenElse): EOExpr = diff --git a/src/main/java/util/Comments.kt b/src/main/java/util/Comments.kt index f6caade0..195e93cc 100644 --- a/src/main/java/util/Comments.kt +++ b/src/main/java/util/Comments.kt @@ -4,6 +4,9 @@ import arrow.core.prependTo import eotree.EOBndExpr import eotree.EOObject +/** + * Prepends comment to the first binding in the list. + */ fun List.comment(comment: String): List = first() .apply { (expr as EOObject).comment = comment } diff --git a/src/main/java/util/Logging.kt b/src/main/java/util/Logging.kt index bbe1e523..a37c2a03 100644 --- a/src/main/java/util/Logging.kt +++ b/src/main/java/util/Logging.kt @@ -2,4 +2,4 @@ package util import mu.KotlinLogging -val logger = KotlinLogging.logger {} +val logger = KotlinLogging.logger("") diff --git a/src/main/java/util/ParseExprTasks.kt b/src/main/java/util/ParseExprTasks.kt deleted file mode 100644 index c26798b1..00000000 --- a/src/main/java/util/ParseExprTasks.kt +++ /dev/null @@ -1,33 +0,0 @@ -package util - -import arrow.core.None -import eotree.EOBndExpr -import eotree.EOObject -import tree.Entity -import kotlin.collections.ArrayList - -class ParseExprTasks { - val tasks = ArrayList>() - val readyBindings = mutableListOf>() - - fun addTask(e: Entity): String { - val name = "e_${e.hashCode()}" - tasks.add(Pair(name, e)) - return name - } - - fun addReadyBinding(obj: EOBndExpr): String { - val name = "e_${obj.hashCode()}" - - val newObj = EOBndExpr( - EOObject( - listOf(), - None, - listOf(obj) - ), - name - ) - readyBindings.add(Pair(name, newObj)) - return name - } -} \ No newline at end of file diff --git a/src/main/java/util/StaticGenerator.kt b/src/main/java/util/StaticGenerator.kt index 97614623..81ef3c6e 100644 --- a/src/main/java/util/StaticGenerator.kt +++ b/src/main/java/util/StaticGenerator.kt @@ -1,23 +1,26 @@ package util import arrow.core.flatten -import arrow.core.flattenOption import eotree.EOBndExpr import lexer.TokenCode import translator.mapClassDeclaration import tree.Declaration.Declaration import tree.Declaration.NormalClassDeclaration +/** + * Maps all static class members to EO bindings, skipping non-static ones. + */ fun generateStatic(clsDec: NormalClassDeclaration): List { - try { - return clsDec.body.declarations + return try { + clsDec.body.declarations .filter { dec: Declaration -> dec.modifiers != null && - dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } != null - } // TODO + dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } != null + } .map { mapClassDeclaration(it) } .flatten() } catch (e: NullPointerException) { - return ArrayList() + logger.warn { "Caught NullPointerException while mapping static class members in generateStatic" } + ArrayList() } } From 785347d1c8dc5f3e1f58009fe7bcb37989b41fe2 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Mon, 16 May 2022 14:47:56 +0300 Subject: [PATCH 21/29] README: updated --- README.md | 421 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 260 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index 02bf6b5f..a53f05e6 100644 --- a/README.md +++ b/README.md @@ -124,19 +124,85 @@ Make sure you have these in sync (*mentioning* (not pointing to) the same `jdk` --- -## Principles of Java to EOLang translation -### Implemented: -- [Class declarations](#class-declarations) -- [Method declarations](#method-declarations) -- [Method invocations](#method-invocations) -- [Local variable declarations](#local-variable-declarations) -- [Field access (via dot-notation)](#field-access) -- [Expressions](#expressions) -- [Instance creation](#instance-creation) - -
- -#### Class declarations +## Examples of Java to EOLang translation + +We use Java language specification document as a foundation for Java feature hierarchy. +Java 16 language specification: [see .pdf file](https://docs.oracle.com/javase/specs/jls/se16/jls16.pdf) + +
+ +--- Ch. 4 - Types, Values, and Variables + + +Table of content: +- [Primitive Types and Values 4.2] - wip +- [Reference Types and Values 4.3] - wip +- [Type Variables 4.4] - wip +- [Parametrized types 4.5] - wip +- [Type erasure 4.6] - wip +- [Reifiable types 4.7] - wip +- [Raw Types 4.8] - wip +- [Intersection Types 4.9] - wip +- [Subtyping 4.10] - wip +
+ +
+ +--- Ch. 5 - Conversions and Contexts + + +Table of content: +- [Assignment Contexts 5.2] - wip +- [Invocation Contexts 5.3] - wip +- [String Contexts 5.4] - wip +- [Casting Contexts 5.5] - wip +- [Numeric Contexts 5.6] - wip +
+ +
+ +--- Ch. 6 - Names + + +Table of content: +- [Declarations 6.1] - wip +- [Names and Identifiers 6.2] - wip +- [Scope of a Declaration 6.3] - wip +- [Shadowing and Obscuring 6.4] - wip +
+ +
+ +--- Ch. 7 - Packages and Modules [WIP] + + +Table of content: +- [Package Members 7.1] - wip +- [Compilation Units 7.3] - wip +- [Package Declarations 7.4] - wip +- [Import Declarations 7.5] - wip +- [Top Level Class and Interface Declarations 7.6] - wip +- [Module Declarations 7.7] - wip +
+ +
+ +--- Ch. 8 - Classes + + +Table of contents: +- [Class declarations 8.1](#class-declarations-81) +- [Class members 8.2] - wip +- [Field declarations 8.3] - wip +- [Method declarations 8.4](#method-declarations-84) +- [Member class and interface declaration 8.5] - wip +- [Instance initializers 8.6] - wip +- [Static initializers 8.7] - wip +- [Constructor declarations 8.8] - wip +- [Enum classes 8.9] - wip +- [Record classes 8.10] - wip + +### Class declarations 8.1 ```java public class Main { } ``` @@ -156,13 +222,16 @@ translates to ```
-#### Method declarations +### Class members 8.2 +### Field declarations 8.3 + +### Method declarations 8.4 ```java public class Main { public static void main(String[] args) { } } ``` -translates to +translates to ```java ... # main :: String -> void @@ -173,64 +242,82 @@ translates to ```
-#### Method invocations +### Member class and interface declarations 8.5 +### Instance initializers 8.6 +### Static initializers 8.7 +### Constructor declarations 8.8 +### Enum classes 8.9 +### Record classes 8.10 + +
+ +
+ +--- Ch. 9 - Interfaces + + +Table of content: +- [Interface Declarations 9.1] - wip +- [Interface Members 9.2] - wip +- [Field (Constant) Declarations 9.3] - wip +- [Method Declarations 9.4] - wip +- [Member Class and Interface Declarations 9.5] - wip +- [Annotation Interfaces 9.6] - wip +- [Annotations 9.7] - wip +- [Functional Interfaces 9.8] - wip +- [Function Types 9.9] - wip +
+ +
+ +--- Ch. 10 - Arrays + + +Table of content: +- [Array Types 10.1] - wip +- [Array Variables 10.2] - wip +- [Array Creation 10.3] - wip +- [Array Access 10.4] - wip +- [Array Initializers 10.6] - wip +- [Array Members 10.7] - wip +- [Class Objects for Arrays 10.8] - wip +
+ +
+ +--- Ch. 11 - Exceptions [WIP] + +
+ +
+ +--- Ch. 14 - Block Statements, and Patterns + + +Table of content: +- [Blocks 14.2] - wip +- [Local Class and Interface Declarations 14.3] - wip +- [Local Variable Declaration 14.4](#local-variable-declaration-144) +- [Statements 14.5] - wip +- [The Empty Statement 14.6] - wip +- [Labeled Statements 14.7] - wip +- [Expression Statements 14.8] - wip +- [The IF Statement 14.9] - wip +- [The assert Statement 14.10] - wip +- [The switch Statement 14.11] - wip +- [The while Statement 14.12] - wip +- [The do Statement 14.13] - wip +- [The for Statement 14.14] - wip +- [The break Statement 14.15] - wip +- [The continue Statement 14.16] - wip +- [The return Statement 14.17] - wip + +### Local Variable Declaration 14.4 ```java public class Main { - public static void main(String[] args) { - method(1.0f, new Object()); - } - int method (float a, Object b) { - return a; - } -} -``` -translates to -```java -+alias stdlib.primitives.prim__float -+alias prim__int -+alias stdlib.lang.class__Object - -[] > class__Main - class__Object > super - super > @ - [] > new - [] > this - class__Object.new > super - super > @ - # main :: String -> void - [this args] > main - seq > @ - s206835546 - [] > s206835546 - method > @ - l758013696 - inst1473611564 - [] > l758013696 - prim__float.constructor_2 > @ - prim__float.new - 1.0 - [] > inst1473611564 - Object.constructor > @ - Object.new - # method :: float -> Object -> int - [this a b] > method - seq > @ - s558187323 - [] > s558187323 - s_r680576081 > @ - [] > s_r680576081 - a > @ - seq > @ - this -``` -
- -#### Local variable declarations -```java -public class Main { public static void main(String[] args) { int local = 5; - } + } } ``` translates to @@ -255,13 +342,26 @@ translates to ```
-#### Field access +
+ +
+ +--- Ch. 15 - Expressions + + +Table of content: +- [Instance Creation 15.9](#instance-creation-159) +- [Field Access 15.11](#field-access-1511) +- [Method invocations 15.12](#method-invocations-1512) + +### Instance Creation 15.9 ```java -public class Main { +public class Main { public static void main(String[] args) { - new SomeClass().localVar.otherVar; + new SomeClass(param1, "string", new Object()); } } +class SomeClass { ... } ``` translates to ```java @@ -269,24 +369,31 @@ translates to # main :: String -> void [this args] > main seq > @ - s756185697 - [] > s756185697 - f_a1308109015.otherVar > @ - [] > f_a1308109015 - inst300031246.localVar > @ - [] > inst300031246 - SomeClass.constructor > @ - SomeClass.new + s599491651 + [] > s599491651 + class__SomeClass.constructor > @ + class__SomeClass.new + s_r1161667116 + l1898220577 + inst1143371233 + [] > s_r1161667116 + param1 > @ + [] > l1898220577 + class__String.constructor_2 > @ + class__String.new + "string" + [] > inst1143371233 + class__Object.constructor > @ + class__Object.new ... ```
-#### Expressions +### Field Access 15.11 ```java -public class Main { +public class Main { public static void main(String[] args) { - int a = 1; - int expr = 1 + 2.0f * 3 - (--a) / 3.0; + new SomeClass().localVar.otherVar; } } ``` @@ -296,94 +403,86 @@ translates to # main :: String -> void [this args] > main seq > @ - d148912029 - d604125138 - prim__int.constructor_1 > a - prim__int.new - [] > d148912029 - a.write > @ - i_s521960438 - [] > i_s521960438 - l726950788 > @ - [] > l726950788 - prim__int.constructor_2 > @ - prim__int.new - 1 - prim__int.constructor_1 > expr - prim__int.new - [] > d604125138 - expr.write > @ - i_s631659383 - [] > i_s631659383 - b720167805 > @ - [] > b720167805 - b1466073198.sub > @ - b398690014 - [] > b1466073198 - l1526298704.add > @ - b1593180232 - [] > l1526298704 - prim__int.constructor_2 > @ - prim__int.new - 1 - [] > b1593180232 - l492079624.mul > @ - l380242442 - [] > l492079624 - prim__float.constructor_2 > @ - prim__float.new - 2.0 - [] > l380242442 - prim__int.constructor_2 > @ - prim__int.new - 3 - [] > b398690014 - p1077199500.div > @ - l240166646 - [] > p1077199500 - s_r351028485 > @ - [] > s_r351028485 - a > @ - [] > l240166646 - prim__float.constructor_2 > @ - prim__float.new - 3.0 + s756185697 + [] > s756185697 + f_a1308109015.otherVar > @ + [] > f_a1308109015 + inst300031246.localVar > @ + [] > inst300031246 + SomeClass.constructor > @ + SomeClass.new ... ```
-#### Instance creation +### Method invocations 15.12 ```java -public class Main { +public class Main { public static void main(String[] args) { - new SomeClass(param1, "string", new Object()); + method(1.0f, new Object()); + } + int method (float a, Object b) { + return a; } } ``` translates to ```java -... -# main :: String -> void -[this args] > main - seq > @ - s599491651 - [] > s599491651 - class__SomeClass.constructor > @ - class__SomeClass.new - s_r1161667116 - l1898220577 - inst1143371233 - [] > s_r1161667116 - param1 > @ - [] > l1898220577 - class__String.constructor_2 > @ - class__String.new - "string" - [] > inst1143371233 - class__Object.constructor > @ - class__Object.new -... ++alias stdlib.primitives.prim__float ++alias prim__int ++alias stdlib.lang.class__Object + +[] > class__Main + class__Object > super + super > @ + [] > new + [] > this + class__Object.new > super + super > @ + # main :: String -> void + [this args] > main + seq > @ + s206835546 + [] > s206835546 + method > @ + l758013696 + inst1473611564 + [] > l758013696 + prim__float.constructor_2 > @ + prim__float.new + 1.0 + [] > inst1473611564 + Object.constructor > @ + Object.new + # method :: float -> Object -> int + [this a b] > method + seq > @ + s558187323 + [] > s558187323 + s_r680576081 > @ + [] > s_r680576081 + a > @ + seq > @ + this ```
- +
+ +
+ +--- Ch. 16 - Definite Assignments [WIP] + +
+ +
+ +--- Ch. 17 - Threads and Locks [EO support?] + +
+ +
+ +--- Ch. 18 - Type inference [WIP] + +
From d5645b821d809747cc2d567d9e9a6d5ac52d0777 Mon Sep 17 00:00:00 2001 From: Egor Klementev Date: Mon, 16 May 2022 17:58:39 +0300 Subject: [PATCH 22/29] FIXES: readme and fixes --- README.md | 292 +++++++++++++++++++++++- src/main/java/parser/TreeMappings.kt | 20 +- src/main/java/translator/Expressions.kt | 4 + 3 files changed, 312 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a53f05e6..313e40af 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Java 16 language specification: [see .pdf file](https://docs.oracle.com/javase/s Table of content: -- [Primitive Types and Values 4.2] - wip +- [Primitive Types and Values 4.2](#primitive-types-and-values-42) - wip - [Reference Types and Values 4.3] - wip - [Type Variables 4.4] - wip - [Parametrized types 4.5] - wip @@ -144,6 +144,56 @@ Table of content: - [Raw Types 4.8] - wip - [Intersection Types 4.9] - wip - [Subtyping 4.10] - wip + +### Primitive Types and Values 4.2 +```java +public class IncrementOperator { + public static void main(String[] args) { + int a = 5; + System.out.println(a++); + System.out.println(++a); + System.out.println("passed"); + } +} +``` +maps to +```java +# main :: String -> void +[this args] > main + seq > @ + d902830499 + s2040467681 + s341796579 + s825936265 + prim__int.constructor_1 > a + prim__int.new + [] > d902830499 + a.write > @ + i_s1754662105 + [] > i_s1754662105 + l403147759 > @ + [] > l403147759 + prim__int.constructor_2 > @ + prim__int.new + 5 + [] > s2040467681 + class__System.out.println > @ + s_r1278677872 + [] > s_r1278677872 + a > @ + [] > s341796579 + class__System.out.println > @ + s_r807657332 + [] > s_r807657332 + a > @ + [] > s825936265 + class__System.out.println > @ + l1164107853 + [] > l1164107853 + class__String.constructor_2 > @ + class__String.new + "passed" +```
@@ -350,10 +400,214 @@ translates to Table of content: +- [Evaluation order 15.7](#evaluation-order-157) +- [Primary Expressions 15.8](#primary-expressions-158) - [Instance Creation 15.9](#instance-creation-159) +- [Arrays 15.10](#arrays-1510) - [Field Access 15.11](#field-access-1511) - [Method invocations 15.12](#method-invocations-1512) +### Evaluation Order 15.7 +```java +public class SimpleLeftHandOperandIsEvaluatedFirst { + public static void main(String[] args) { + int i = 2; + int j = (i=3) * i; + System.out.println(j); + System.out.println("passed"); + } +} +``` +maps to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d823723302 + d1051876890 + s25536233 + s164974746 + prim__int.constructor_1 > i + prim__int.new + [] > d823723302 + i.write > @ + i_s1714078840 + [] > i_s1714078840 + l1732502545 > @ + [] > l1732502545 + prim__int.constructor_2 > @ + prim__int.new + 2 + prim__int.constructor_1 > j + prim__int.new + [] > d1051876890 + j.write > @ + i_s1199262943 + [] > i_s1199262943 + b2009221452 > @ + [] > b2009221452 + p257513673.mul > @ + s_r590845366 + [] > p257513673 + b1052195003 > @ + [] > b1052195003 + s_r1541049864.write > @ + l511707818 + [] > s_r1541049864 + i > @ + [] > l511707818 + prim__int.constructor_2 > @ + prim__int.new + 3 + [] > s_r590845366 + i > @ + [] > s25536233 + class__System.out.println > @ + s_r116405378 + [] > s_r116405378 + j > @ + [] > s164974746 + class__System.out.println > @ + l396283472 + [] > l396283472 + class__String.constructor_2 > @ + class__String.new + "passed" +... +``` + +### Primary Expressions 15.8 +```java +public class BooleanLiteral { + public static void main(String[] args) { + boolean a = true; + boolean b = false; + System.out.println("passed"); + } +} +``` +maps to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d1819063424 + d690686166 + s1165303897 + prim__boolean.constructor_1 > a + prim__boolean.new + [] > d1819063424 + a.write > @ + i_s1011279482 + [] > i_s1011279482 + l208866101 > @ + [] > l208866101 + prim__boolean.constructor_2 > @ + prim__boolean.new + TRUE + prim__boolean.constructor_1 > b + prim__boolean.new + [] > d690686166 + b.write > @ + i_s576020159 + [] > i_s576020159 + l921420643 > @ + [] > l921420643 + prim__boolean.constructor_2 > @ + prim__boolean.new + FALSE + [] > s1165303897 + class__System.out.println > @ + l887750041 + [] > l887750041 + class__String.constructor_2 > @ + class__String.new + "passed" +... +``` +
+ +```java +public class ComplexParenthExpression { + public static void main(String[] args) { + int a = (10 + ((((5 * (2 + (2))))))); + System.out.println(a); + System.out.println("passed"); + } +} +``` +maps to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d1365008457 + s678433396 + s928294079 + prim__int.constructor_1 > a + prim__int.new + [] > d1365008457 + a.write > @ + i_s1671179293 + [] > i_s1671179293 + p1609124502 > @ + [] > p1609124502 + b1144068272 > @ + [] > b1144068272 + l1985836631.add > @ + p1948471365 + [] > l1985836631 + prim__int.constructor_2 > @ + prim__int.new + 10 + [] > p1948471365 + p1636506029 > @ + [] > p1636506029 + p758348212 > @ + [] > p758348212 + p817978763 > @ + [] > p817978763 + b1578009262 > @ + [] > b1578009262 + l1735507635.mul > @ + p1362728240 + [] > l1735507635 + prim__int.constructor_2 > @ + prim__int.new + 5 + [] > p1362728240 + b1798219673 > @ + [] > b1798219673 + l1092572064.add > @ + p728885526 + [] > l1092572064 + prim__int.constructor_2 > @ + prim__int.new + 2 + [] > p728885526 + l922511709 > @ + [] > l922511709 + prim__int.constructor_2 > @ + prim__int.new + 2 + [] > s678433396 + class__System.out.println > @ + s_r331994761 + [] > s_r331994761 + a > @ + [] > s928294079 + class__System.out.println > @ + l1647809929 + [] > l1647809929 + class__String.constructor_2 > @ + class__String.new + "passed" +... +``` + ### Instance Creation 15.9 ```java public class Main { @@ -389,6 +643,42 @@ translates to ```
+### Arrays 15.10 +```java +public class SimpleIntegerArray { + public static void main(String[] args) { + int[] array = new int[5]; + System.out.println("passed"); + } +} +``` +maps to +```java +... +# main :: String -> void +[this args] > main + seq > @ + d775081157 + s693958407 + prim__int.constructor_1 > array + prim__int.new + [] > d775081157 + array.write > @ + i_s1955021259 + [] > i_s1955021259 + arr1044705957 > @ + array > temp_placeholder + [] > s693958407 + class__System.out.println > @ + l288379405 + [] > l288379405 + class__String.constructor_2 > @ + class__String.new + "passed" +... +``` +
+ ### Field Access 15.11 ```java public class Main { diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 49797892..b200bef4 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -79,7 +79,13 @@ fun MethodDeclarationContext.toDeclaration(): Declaration = ) fun MethodBodyContext.toBlock(): Block = - block()?.toBlock() ?: Block(ArrayList(), BlockStatements(null)) + if (block() == null) { + val blockStmnts = BlockStatements(null) + blockStmnts.blockStatements.removeIf { it == null } + Block(ArrayList(), blockStmnts) + } else { + block().toBlock() + } fun FormalParametersContext.toParameterDeclarations(): ParameterDeclarations? = formalParameterList()?.toParameterDeclarations() @@ -216,6 +222,7 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = QUESTION -> Token(TokenCode.Question) INC -> Token(TokenCode.PlusPlus) DEC -> Token(TokenCode.MinusMinus) + VAR -> Token(TokenCode.Var) else -> throw Exception("unsupported token: $text ($type)") } @@ -278,7 +285,8 @@ fun ExpressionContext.toExpression() : Expression { } fun CreatorContext.toExpression() : Expression { - return InstanceCreation( + if (classCreatorRest() != null) + return InstanceCreation( null, // No type arguments for now TypeName( CompoundName(createdName().identifier().map { it.IDENTIFIER().text }.toList()), @@ -287,6 +295,12 @@ fun CreatorContext.toExpression() : Expression { classCreatorRest().arguments()?.toArgList(), classCreatorRest().classBody()?.toDeclarations() ) + if (arrayCreatorRest() != null) + return ArrayCreation( + null, + arrayCreatorRest().arrayInitializer()?.toInitializerArray() + ) + return SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } fun ArgumentsContext.toArgList() : ArgumentList { @@ -321,7 +335,7 @@ fun MethodCallContext.toExpression(expr: Expression?) : Expression { } fun IdentifierContext.toExpression() : Expression = - SimpleReference(CompoundName(IDENTIFIER().text)) + SimpleReference(CompoundName(IDENTIFIER()?.text ?: "var")) // A specific case fun PrimaryContext.toParenthesized(): Parenthesized? = if (LPAREN() != null && RPAREN() != null) { diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index 957a3208..69430e48 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -33,6 +33,8 @@ fun mapExpression(expr: Expression, name: String): List = mapParenthesized(expr, name) is InstanceCreation -> mapInstanceCreation(expr, name) + is ArrayCreation -> + listOf(EOBndExpr(EOCopy("array"), "temp_placeholder")) else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } @@ -59,6 +61,8 @@ fun constructExprName(expr: Expression): String = "p${expr.hashCode()}" is InstanceCreation -> "inst${expr.hashCode()}" + is ArrayCreation -> + "arr${expr.hashCode()}" else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } From cfb0fb72d19c9266cb1a8892ad393a25e8bd04dd Mon Sep 17 00:00:00 2001 From: someilay Date: Mon, 16 May 2022 20:01:05 +0300 Subject: [PATCH 23/29] FEATURE: support of arrays & minor fixes --- .gitignore | 1 + src/main/java/parser/TreeMappings.kt | 283 ++++++++++++------ src/main/java/translator/Declarations.kt | 30 +- src/main/java/translator/Expressions.kt | 49 +++ src/main/java/translator/Initializers.kt | 28 +- src/main/java/translator/MethodInvocations.kt | 47 ++- .../translator/preprocessor/Preprocessor.kt | 45 ++- src/main/java/util/PrimitiveTypesFinder.kt | 15 + 8 files changed, 372 insertions(+), 126 deletions(-) diff --git a/.gitignore b/.gitignore index 1b2dbb19..309b7c15 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ out +input .gradle .idea build diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 49797892..7c69172d 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -17,7 +17,7 @@ import tree.Statement.* import tree.Type.* import kotlin.reflect.typeOf -fun CompilationUnitContext.toCompilationUnit() : CompilationUnit { +fun CompilationUnitContext.toCompilationUnit(): CompilationUnit { val imports = ArrayList(importDeclaration().map { it.toImportDeclaration() }) val importDecls = ImportDeclarations(imports.removeFirstOrNull()) imports.forEach { importDecls.add(it) } @@ -29,19 +29,19 @@ fun CompilationUnitContext.toCompilationUnit() : CompilationUnit { topLevelCmpnts.components.removeIf { it == null } return SimpleCompilationUnit( - importDecls, - topLevelCmpnts + importDecls, + topLevelCmpnts ) } -fun TypeDeclarationContext.toTopLevelComponent() : TopLevelComponent? = +fun TypeDeclarationContext.toTopLevelComponent(): TopLevelComponent? = if (classDeclaration() != null) { TopLevelComponent(classDeclaration().toClassDeclaration()) } else { null // throw java.lang.Exception("Cannot translate") // FIXME } -fun ClassDeclarationContext.toClassDeclaration() : ClassDeclaration = +fun ClassDeclarationContext.toClassDeclaration(): ClassDeclaration = NormalClassDeclaration( identifier().toToken(), typeParameters()?.toTypeParameters(), @@ -50,7 +50,7 @@ fun ClassDeclarationContext.toClassDeclaration() : ClassDeclaration = classBody().toDeclarations() ) -fun ClassBodyContext.toDeclarations() : Declarations { +fun ClassBodyContext.toDeclarations(): Declarations { val clsBodyDecls = ArrayList(this.classBodyDeclaration().mapNotNull { it.toDeclaration() }) val decls = Declarations(clsBodyDecls.removeFirstOrNull()) clsBodyDecls.forEach { decls.add(it) } @@ -64,7 +64,7 @@ fun ClassBodyDeclarationContext.toDeclaration(): Declaration? = fun MemberDeclarationContext.toDeclaration(modifiers: List?): Declaration? = methodDeclaration()?.toDeclaration() - // FIXME: support other declarations +// FIXME: support other declarations fun MethodDeclarationContext.toDeclaration(): Declaration = MethodDeclaration( @@ -84,7 +84,7 @@ fun MethodBodyContext.toBlock(): Block = fun FormalParametersContext.toParameterDeclarations(): ParameterDeclarations? = formalParameterList()?.toParameterDeclarations() -fun FormalParameterListContext.toParameterDeclarations() : ParameterDeclarations { +fun FormalParameterListContext.toParameterDeclarations(): ParameterDeclarations { val formalParams = ArrayList(formalParameter().map { it.toParameterDeclaration() }) val paramDecls = ParameterDeclarations(formalParams.removeFirstOrNull()) formalParams.forEach { paramDecls.add(it) } @@ -130,61 +130,87 @@ fun LocalTypeDeclarationContext.toDeclaration(): Declaration = fun StatementContext.toStatement(): Statement = when (this) { - is StatementWhileContext -> While(null /* FIXME */, + is StatementWhileContext -> While( + null /* FIXME */, parExpression().expression().toExpression(), - statement().toStatement()) - is StatementIfContext -> IfThenElse(null, + statement().toStatement() + ) + is StatementIfContext -> IfThenElse( + null, parExpression().expression().toExpression(), statement(0).toStatement(), - statement(1)?.toStatement()) - is StatementExpressionContext -> StatementExpression(null, - expression().toExpression()) - is StatementAssertContext -> Assert(null, + statement(1)?.toStatement() + ) + is StatementExpressionContext -> StatementExpression( + null, + expression().toExpression() + ) + is StatementAssertContext -> Assert( + null, this.expression(0).toExpression(), - this.expression(1)?.toExpression()) + this.expression(1)?.toExpression() + ) is StatementBreakContext -> Break(null, identifier()?.toToken()) is StatementContinueContext -> Continue(null, identifier()?.toToken()) - is StatementForContext -> StatementExpression(null, SimpleReference(CompoundName("for_loop_placeholder"))) /* FIXME */ + is StatementForContext -> StatementExpression( + null, + SimpleReference(CompoundName("for_loop_placeholder")) + ) /* FIXME */ is StatementBlockLabelContext -> block().toBlock() is StatementDoContext -> Do(null, statement().toStatement(), parExpression().expression().toExpression()) is StatementReturnContext -> Return(null, expression()?.toExpression()) - is StatementIdentifierLabelContext -> StatementExpression(null, SimpleReference(CompoundName("identifier_label_placeholder"))) /* FIXME */ - is StatementSemiContext -> StatementExpression(null, SimpleReference(CompoundName("semi_noop_placeholder"))) /* FIXME */ - is StatementSwitchContext -> StatementExpression(null, SimpleReference(CompoundName("switch_statement_placeholder"))) /* FIXME */ + is StatementIdentifierLabelContext -> StatementExpression( + null, + SimpleReference(CompoundName("identifier_label_placeholder")) + ) /* FIXME */ + is StatementSemiContext -> StatementExpression( + null, + SimpleReference(CompoundName("semi_noop_placeholder")) + ) /* FIXME */ + is StatementSwitchContext -> StatementExpression( + null, + SimpleReference(CompoundName("switch_statement_placeholder")) + ) /* FIXME */ is StatementSwitchExpressionContext -> StatementExpression(null, switchExpression().toExpression()) - /* Switch(null, - this.parExpression().expression().toExpression(), - SwitchBlocks(ArrayList(switchBlockStatementGroup().map { it.toSwitchBlock() })), - 0 /* FIXME: switchLabels */ - ) */ - is StatementTryResourceSpecificationContext -> StatementExpression(null, SimpleReference(CompoundName("try_resource_placeholder"))) /* FIXME */ - is StatementTryBlockContext -> StatementExpression(null, SimpleReference(CompoundName("try_block_placeholder"))) /* FIXME */ + /* Switch(null, + this.parExpression().expression().toExpression(), + SwitchBlocks(ArrayList(switchBlockStatementGroup().map { it.toSwitchBlock() })), + 0 /* FIXME: switchLabels */ + ) */ + is StatementTryResourceSpecificationContext -> StatementExpression( + null, + SimpleReference(CompoundName("try_resource_placeholder")) + ) /* FIXME */ + is StatementTryBlockContext -> StatementExpression( + null, + SimpleReference(CompoundName("try_block_placeholder")) + ) /* FIXME */ else -> StatementExpression(null, SimpleReference(CompoundName("statement_placeholder"))) /* FIXME */ // else -> throw Exception("Unsupported statement") /* FIXME */ } -fun SwitchExpressionContext.toExpression() : Expression = +fun SwitchExpressionContext.toExpression(): Expression = SimpleReference(CompoundName("switch_expression_placeholder")) /* FIXME */ - /* FIXME: - SwitchExpression( - parExpression().expression().toExpression(), - ??? - ) */ +/* FIXME: +SwitchExpression( + parExpression().expression().toExpression(), + ??? +) */ -fun SwitchBlockStatementGroupContext.toSwitchBlock() : SwitchBlock = +fun SwitchBlockStatementGroupContext.toSwitchBlock(): SwitchBlock = SwitchBlock( ArrayList(this.switchLabel().map { it.toSwitchLabel() }), null ) -fun SwitchLabelContext.toSwitchLabel() : SwitchLabel = +fun SwitchLabelContext.toSwitchLabel(): SwitchLabel = SwitchLabel( constantExpression?.toExpression() ?: enumConstantName?.toCompoundName()?.toExpression() ) -fun org.antlr.v4.runtime.Token.toCompoundName() : CompoundName = CompoundName(text) -fun org.antlr.v4.runtime.Token.toToken() : Token = +fun org.antlr.v4.runtime.Token.toCompoundName(): CompoundName = CompoundName(text) +fun org.antlr.v4.runtime.Token.toToken(): Token = when (type) { ADD -> Token(TokenCode.Plus) MUL -> Token(TokenCode.Star) @@ -221,7 +247,7 @@ fun org.antlr.v4.runtime.Token.toToken() : Token = fun CompoundName.toExpression(): Expression = SimpleReference(this) -fun ExpressionContext.toBinaryExpression() : Binary? { +fun ExpressionContext.toBinaryExpression(): Binary? { val expr0 = expression(0)?.toExpression() val expr1 = expression(1)?.toExpression() val operand = terminal(0)?.symbol @@ -231,7 +257,7 @@ fun ExpressionContext.toBinaryExpression() : Binary? { null } -fun ExpressionContext.toUnaryPrefixPostfix() : Expression? { +fun ExpressionContext.toUnaryPrefixPostfix(): Expression? { val expr = expression(0)?.toExpression() val operand = terminal(0)?.symbol return if (expr != null && operand != null) { @@ -247,23 +273,34 @@ fun ExpressionContext.toUnaryPrefixPostfix() : Expression? { } } -fun ExpressionContext.toExpression() : Expression { +fun ExpressionContext.toArrayAccess(): ArrayAccess? { + if (LBRACK() != null && RBRACK() != null) { + return ArrayAccess( + expression(0).toExpression(), + expression(1).toExpression() + ) + } + return null +} + +fun ExpressionContext.toExpression(): Expression { val expr0 = - expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() - ?: creator()?.toExpression() ?: methodCall()?.toExpression(null) - ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: expression(0)?.toExpression() + ?: primary()?.toExpression() ?: identifier()?.toExpression() ?: creator()?.toExpression() + ?: methodCall()?.toExpression(null) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ if (this.bop != null) { val expr1 = - expression(1)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() - ?: creator()?.toExpression() ?: methodCall()?.toExpression(expr0) - ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: expression(1)?.toExpression() + ?: primary()?.toExpression() + ?: identifier()?.toExpression() ?: creator()?.toExpression() ?: methodCall()?.toExpression(expr0) + ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ return if (this.bop.text == ".") { when (expr1) { is MethodInvocation -> expr1 is SimpleReference -> FieldAccess( - expr0, - SUPER() != null, - Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable + expr0, + SUPER() != null, + Token(TokenCode.Identifier, expr1.compoundName.names[0]) // FIXME: questionable ) else -> SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ } @@ -277,19 +314,41 @@ fun ExpressionContext.toExpression() : Expression { } } -fun CreatorContext.toExpression() : Expression { - return InstanceCreation( +fun CreatorContext.toExpression(): Expression { + val arrayCreatorRestContext = arrayCreatorRest() + val classCreatorRestContext = classCreatorRest() + + val createdNameContext = createdName() + val createdNameIdentifiers = createdNameContext.identifier() + val primitiveTypeContext = createdNameContext.primitiveType() + + return if (classCreatorRestContext != null) { + InstanceCreation( null, // No type arguments for now TypeName( - CompoundName(createdName().identifier().map { it.IDENTIFIER().text }.toList()), - null // No type arguments for now + CompoundName(createdNameIdentifiers.map { it.IDENTIFIER().text }.toList()), + null // No type arguments for now ), - classCreatorRest().arguments()?.toArgList(), - classCreatorRest().classBody()?.toDeclarations() - ) + classCreatorRestContext.arguments()?.toArgList(), + classCreatorRestContext.classBody()?.toDeclarations() + ) + } else if (arrayCreatorRestContext != null) { + ArrayCreation( + primitiveTypeContext?.toType() + ?: TypeName( + CompoundName(createdNameIdentifiers.map { it.IDENTIFIER().text }.toList()), + null // No type arguments for now + ), + arrayCreatorRestContext.arrayInitializer()?.toInitializerArray() ?: InitializerArray( + InitializerSimple(arrayCreatorRestContext.expression(0).toExpression()) + ) + ) + } else { + SimpleReference(CompoundName("unknown_creator_context_placeholder")) + } } -fun ArgumentsContext.toArgList() : ArgumentList { +fun ArgumentsContext.toArgList(): ArgumentList { return if (expressionList() == null) { val args = ArgumentList(null) args.arguments.removeIf { it == null } @@ -303,7 +362,7 @@ fun ArgumentsContext.toArgList() : ArgumentList { } } -fun MethodCallContext.toExpression(expr: Expression?) : Expression { +fun MethodCallContext.toExpression(expr: Expression?): Expression { val exprLst = if (expressionList() == null) ArrayList(listOf()) else @@ -312,16 +371,16 @@ fun MethodCallContext.toExpression(expr: Expression?) : Expression { exprLst.forEach { argList.add(it) } argList.arguments.removeIf { it == null } return MethodInvocation( - expr, - SUPER() != null, - null, // TODO: type arguments are somewhere else - identifier().toToken(), - argList + expr, + SUPER() != null, + null, // TODO: type arguments are somewhere else + identifier().toToken(), + argList ) } -fun IdentifierContext.toExpression() : Expression = - SimpleReference(CompoundName(IDENTIFIER().text)) +fun IdentifierContext.toExpression(): Expression = + SimpleReference(CompoundName(IDENTIFIER().text)) fun PrimaryContext.toParenthesized(): Parenthesized? = if (LPAREN() != null && RPAREN() != null) { @@ -335,25 +394,36 @@ fun PrimaryContext.toParenthesized(): Parenthesized? = null } -fun PrimaryContext.toExpression() : Expression = - this.toParenthesized() ?: - expression()?.toExpression() ?: - identifier()?.toExpression() ?: - THIS()?.let { _ -> This(null) } ?: +fun PrimaryContext.toExpression(): Expression = + this.toParenthesized() ?: expression()?.toExpression() ?: identifier()?.toExpression() ?: THIS()?.let { _ -> + This( + null + ) + } ?: /* FIXME: super */ - literal()?.toLiteral() ?: - identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } ?: - SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ + literal()?.toLiteral() ?: identifier()?.let { id -> SimpleReference(CompoundName(id.text)) } ?: SimpleReference( + CompoundName("expression_placeholder") + ) /* FIXME */ /* FIXME: typeOrVoid . CLASS */ - /* FIXME: nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) */ - -fun LiteralContext.toLiteral() : Literal? = - BOOL_LITERAL()?.text?.let { txt -> Literal(Token(if (txt == "true") { TokenCode.True } else { TokenCode.False })) } ?: - integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text))} ?: - NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } ?: - floatLiteral()?.let { x -> Literal(Token(TokenCode.FloatingLiteral, x.text)) } ?: - STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text.drop(1).dropLast(1))) } ?: - Literal(Token(TokenCode.IntegerLiteral, "123456")) ?: /* FIXME: support other literals */ +/* FIXME: nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) */ + +fun LiteralContext.toLiteral(): Literal? = + BOOL_LITERAL()?.text?.let { txt -> + Literal( + Token( + if (txt == "true") { + TokenCode.True + } else { + TokenCode.False + } + ) + ) + } ?: integerLiteral()?.DECIMAL_LITERAL()?.let { n -> Literal(Token(TokenCode.IntegerLiteral, n.text)) } + ?: NULL_LITERAL()?.let { _ -> Literal(Token(TokenCode.Null)) } + ?: floatLiteral()?.let { x -> Literal(Token(TokenCode.FloatingLiteral, x.text)) } + ?: STRING_LITERAL()?.let { s -> Literal(Token(TokenCode.StringLiteral, s.text.drop(1).dropLast(1))) } ?: Literal( + Token(TokenCode.IntegerLiteral, "123456") + ) ?: /* FIXME: support other literals */ throw Exception("unsupported literal $text") /* FIXME */ fun LocalVariableDeclarationContext.toDeclaration(): Declaration = @@ -372,7 +442,7 @@ fun IdentifierContext.toVariableDeclarators(expression: ExpressionContext): Vari fun IdentifierContext.toVariableDeclarator(expression: ExpressionContext): VariableDeclarator = VariableDeclarator(this.toToken(), null, InitializerSimple(expression.toExpression())) -fun VariableDeclaratorsContext.toVariableDeclarators() : VariableDeclarators { +fun VariableDeclaratorsContext.toVariableDeclarators(): VariableDeclarators { val varDeclsLst = ArrayList(this.variableDeclarator().map { it.toVariableDeclarator() }) val varDecls = VariableDeclarators(varDeclsLst.removeFirstOrNull()) varDeclsLst.forEach { varDecls.add(it) } @@ -380,13 +450,13 @@ fun VariableDeclaratorsContext.toVariableDeclarators() : VariableDeclarators { return varDecls } -fun VariableDeclaratorContext.toVariableDeclarator() : VariableDeclarator { +fun VariableDeclaratorContext.toVariableDeclarator(): VariableDeclarator { // val dimLst = ArrayList(variableDeclaratorId().LBRACK().size) val dims = Dims() return VariableDeclarator( - this.variableDeclaratorId().identifier().toToken(), - dims, - this.variableInitializer()?.toInitializer() + this.variableDeclaratorId().identifier().toToken(), + dims, + this.variableInitializer()?.toInitializer() ) } @@ -394,7 +464,7 @@ fun VariableInitializerContext.toInitializer(): Initializer = arrayInitializer()?.toInitializerArray() ?: InitializerSimple(expression().toExpression()) -fun ArrayInitializerContext.toInitializerArray() : InitializerArray { +fun ArrayInitializerContext.toInitializerArray(): InitializerArray { val varInitLst = ArrayList(variableInitializer().map { it.toInitializer() }) val initArr = InitializerArray(varInitLst.removeFirstOrNull()) varInitLst.forEach { initArr.add(it) } @@ -402,8 +472,8 @@ fun ArrayInitializerContext.toInitializerArray() : InitializerArray { return initArr } -fun TypeParametersContext.toTypeParameters() : TypeParameters { - val typeLst = ArrayList(this.typeParameter().map { it.toTypeParameter()}) +fun TypeParametersContext.toTypeParameters(): TypeParameters { + val typeLst = ArrayList(this.typeParameter().map { it.toTypeParameter() }) val typeParams = TypeParameters(typeLst.removeFirstOrNull()) typeLst.forEach { typeParams.add(it) } typeParams.typeParameters.removeIf { it == null } @@ -413,7 +483,7 @@ fun TypeParametersContext.toTypeParameters() : TypeParameters { fun TypeParameterContext.toTypeParameter(): TypeParameter = TypeParameter(null /* FIXME */, TypeParameterTail(this.identifier().toToken(), null /* FIXME */)) -fun TypeListContext.toTypeList() : TypeList { +fun TypeListContext.toTypeList(): TypeList { val typeArr = ArrayList(this.typeType().map { it.toType() }) val typeLst = TypeList(typeArr.removeFirstOrNull()) typeArr.forEach { typeLst.add(it) } @@ -428,10 +498,18 @@ fun TypeTypeContext.toType(): Type = else -> throw Exception("not supported") // FIXME: impossible? } -fun TypePrimitiveTypeContext.toType(): Type = - primitiveType().toType() // FIXME: annotations and more? +fun TypePrimitiveTypeContext.toType(): Type { + val leftBrackets = LBRACK() + val rnType = primitiveType().toType() as PrimitiveType + + for (leftBracket in leftBrackets) { + rnType.addDimension(Dim(null, null)) + } + + return rnType // FIXME: annotations? +} -fun TerminalNode.toPrimitiveType() : PrimitiveType = +fun TerminalNode.toPrimitiveType(): PrimitiveType = when (this.symbol.type) { BOOLEAN -> PrimitiveType(Token(TokenCode.Boolean)) CHAR -> PrimitiveType(Token(TokenCode.Char)) @@ -455,16 +533,25 @@ fun PrimitiveTypeContext.toType(): Type = ?: DOUBLE()?.toPrimitiveType() ?: throw Exception("Unsupported primitive type: $this") -fun TypeClassOrInterfaceTypeContext.toType(): Type = - this.classOrInterfaceType().toType() // FIXME +fun TypeClassOrInterfaceTypeContext.toType(): Type { + val leftBrackets = LBRACK() + val rnType = classOrInterfaceType().toType() as TypeName + + for (leftBracket in leftBrackets) { + rnType.addDimension(Dim(null, null)) + } + + return rnType // FIXME: annotations? +} fun ClassOrInterfaceTypeContext.toType(): Type = TypeName( CompoundName(this.identifier().map { it.text }), - this.typeArguments().lastOrNull()?.toTypeArguments() // FIXME: we use last() since we do not support types like A.C + this.typeArguments().lastOrNull() + ?.toTypeArguments() // FIXME: we use last() since we do not support types like A.C ) -fun TypeArgumentsContext.toTypeArguments() : TypeArguments { +fun TypeArgumentsContext.toTypeArguments(): TypeArguments { val typeArgsLst = ArrayList(typeArgument().map { it.toTypeArgument() }) val typeArgs = TypeArguments(typeArgsLst.removeFirstOrNull()) typeArgsLst.forEach { typeArgs.add(it) } diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index 7dfe4ed1..b500f01e 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -65,15 +65,29 @@ fun mapVariableDeclaration(dec: VariableDeclaration, name: String): List { - listOf( - EOBndExpr( - EOCopy( - listOf(decodePrimitiveType(dec.type as PrimitiveType).value, decodeInitializer(dec.initializer)).eoDot(), - listOf(decodePrimitiveType(dec.type as PrimitiveType).value, "new").eoDot() - ), - dec.name + if ((dec.type as PrimitiveType).dimensions.dimensions.isEmpty()) { + listOf( + EOBndExpr( + EOCopy( + listOf( + decodePrimitiveType(dec.type as PrimitiveType).value, + decodeInitializer(dec.initializer) + ).eoDot(), + listOf(decodePrimitiveType(dec.type as PrimitiveType).value, "new").eoDot() + ), + dec.name + ) ) - ) + } else { + listOf( + EOBndExpr( + EOCopy( + EODot("cage"), + ), + dec.name + ) + ) + } } null -> throw IllegalArgumentException("\"var\" declarations are not supported yet") diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index 957a3208..188c6369 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -33,6 +33,10 @@ fun mapExpression(expr: Expression, name: String): List = mapParenthesized(expr, name) is InstanceCreation -> mapInstanceCreation(expr, name) + is ArrayCreation -> + mapArrayCreation(expr, name) + is ArrayAccess -> + mapArrayAccess(expr, name) else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } @@ -59,10 +63,55 @@ fun constructExprName(expr: Expression): String = "p${expr.hashCode()}" is InstanceCreation -> "inst${expr.hashCode()}" + is ArrayCreation -> + "a_c${expr.hashCode()}" + is ArrayAccess -> + "a_a${expr.hashCode()}" else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } +fun mapArrayAccess(access: ArrayAccess, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(access.expression), "get").eoDot(), + listOf(constructExprName(access.size), "v").eoDot() + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(access.expression, constructExprName(access.expression)) + + mapExpression(access.size, constructExprName(access.size)) +} + +fun mapArrayCreation(arrayCreation: ArrayCreation, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + "cannot_get_access_to_array_initializer" // FIXME + ), + "@" + ) + ) + ), + name + ) + ) +} fun mapInstanceCreation(expr: InstanceCreation, name: String): List { return listOf( diff --git a/src/main/java/translator/Initializers.kt b/src/main/java/translator/Initializers.kt index a10df030..25e5003c 100644 --- a/src/main/java/translator/Initializers.kt +++ b/src/main/java/translator/Initializers.kt @@ -8,20 +8,25 @@ import eotree.eoDot import tree.CompoundName import tree.Expression.SimpleReference import tree.Initializer +import tree.InitializerArray import tree.InitializerSimple import util.ParseExprTasks fun mapInitializer(initializer: Initializer, name: String): List { return when (initializer) { is InitializerSimple -> mapInitializerSimple(initializer, name) + is InitializerArray -> mapInitializerArray(initializer, name) else -> - mapInitializerSimple(InitializerSimple(SimpleReference(CompoundName("array_initializer_placeholder"))), name) // FIXME + mapInitializerSimple( + InitializerSimple(SimpleReference(CompoundName("unknown_initializer_placeholder"))), name + ) // FIXME } } fun constructInitName(initializer: Initializer): String { return when (initializer) { is InitializerSimple -> "i_s${initializer.hashCode()}" + is InitializerArray -> "i_a${initializer.hashCode()}" else -> "un_i${initializer.hashCode()}" } @@ -46,3 +51,24 @@ fun mapInitializerSimple(initializerSimple: InitializerSimple, name: String): Li ) ) + mapExpression(initializerSimple.expression, constructExprName(initializerSimple.expression)) } + +fun mapInitializerArray(initializerArray: InitializerArray, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + "*", + initializerArray.initializers.map { constructInitName(it).eoDot() } + ), + "@" + ) + ) + ), + name + ) + ) + initializerArray.initializers.map { mapInitializer(it, constructInitName(it)) }.flatten() +} diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index ddc49a48..bd751ab7 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -11,26 +11,49 @@ import tree.CompoundName import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference -import util.ParseExprTasks -import util.isSystemOutCall -import java.lang.reflect.Field + + +private fun isStaticCall(methodInvocation: MethodInvocation): Boolean { + return when (val methodQualifier = methodInvocation.qualifier) { + is SimpleReference -> { + methodQualifier.compoundName.names.first().contains("class__") && + methodQualifier.compoundName.names.size == 1 + } + is FieldAccess -> { + val fullIdentifier = getFullIdentifier(methodQualifier) + fullIdentifier.first().contains("class__") && fullIdentifier.size == 1 + } + else -> false + } +} + +private fun getFullIdentifier(fieldAccess: FieldAccess): List { + return ( + when (fieldAccess.expression) { + is FieldAccess -> { + getFullIdentifier(fieldAccess.expression as FieldAccess) + } + is SimpleReference -> { + (fieldAccess.expression as SimpleReference).compoundName.names + } + else -> { + listOf() + } + } + ) + listOf(fieldAccess.identifier) +} + // TODO: create state object to store binding of expression fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List { require(!methodInvocation.superSign) { "Super sign isn't supported yet" } require(methodInvocation.typeArguments == null) { "Type arguments aren't supported yet" } - val isStaticCall = !isSystemOutCall(methodInvocation) + val isStaticCall = isStaticCall(methodInvocation) val src: EODot = when (val methodQualifier = methodInvocation.qualifier) { is SimpleReference -> (methodQualifier.compoundName.names + listOf(methodInvocation.name)).eoDot() - is FieldAccess -> - when (val qualExpr = methodQualifier.expression) { - is SimpleReference -> CompoundName( - qualExpr.compoundName.names + listOf(methodQualifier.identifier, methodInvocation.name) - ).eoDot() - else -> throw IllegalArgumentException("Unsupported yet") - } + is FieldAccess -> (getFullIdentifier(methodQualifier) + listOf(methodInvocation.name)).eoDot() null -> methodInvocation.name.eoDot() else -> throw IllegalArgumentException("Unsupported method qualifier!") @@ -41,7 +64,7 @@ fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List< methodQualifier.compoundName.names.dropLast(1).eoDot() else "this".eoDot() - is FieldAccess -> methodQualifier.identifier.eoDot() + is FieldAccess -> getFullIdentifier(methodQualifier).eoDot() null -> "this".eoDot() else -> throw IllegalArgumentException("Unsupported method qualifier!") diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index d6fb6bfe..308570c2 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -12,9 +12,13 @@ import tree.Expression.Primary.InstanceCreation import tree.Expression.Primary.MethodInvocation import tree.Expression.SimpleReference import tree.InitializerSimple +import tree.Statement.Block import tree.Statement.BlockStatement +import tree.Statement.Do +import tree.Statement.IfThenElse import tree.Statement.Statement import tree.Statement.StatementExpression +import tree.Statement.While import tree.Type.PrimitiveType import tree.Type.Type import tree.Type.TypeName @@ -26,15 +30,16 @@ import kotlin.collections.HashSet /** * @property classNames - * @property stdTokensNeededForAlias + * @property tokensNeededForAlias * @property stdTokensForCurrentAlias */ data class PreprocessorState( val classNames: HashMap = hashMapOf( "Object" to TokenCodes.CLASS__OBJECT.value, "System" to TokenCodes.CLASS__SYSTEM.value, + "String" to TokenCodes.CLASS__STRING.value ), - val stdTokensNeededForAlias: HashSet = hashSetOf( + val tokensNeededForAlias: HashSet = hashSetOf( TokenCodes.CLASS__OBJECT.value, TokenCodes.CLASS__SYSTEM.value, TokenCodes.PRIM__INT.value, @@ -48,6 +53,8 @@ data class PreprocessorState( TokenCodes.PRIM__DOUBLE.value, TokenCodes.PRIM__SHORT.value ), + val tokensToImportPath: Map = TokenCodes.values() + .associate { it.value to it.importPath }, val stdTokensForCurrentAlias: HashSet = hashSetOf( TokenCodes.CLASS__OBJECT.importPath // We need it always ), @@ -157,8 +164,7 @@ private fun preprocessClassDecl(state: PreprocessorState, clsDec: ClassDeclarati private fun preprocessMethodDecl(state: PreprocessorState, methodDecl: MethodDeclaration) { try { - methodDecl.methodBody.block.blockStatements - .map { blockStmt: BlockStatement -> preprocessBlockStmt(state, blockStmt) } + preprocessBlock(state, methodDecl.methodBody) when (methodDecl.type) { is PrimitiveType -> { @@ -173,6 +179,11 @@ private fun preprocessMethodDecl(state: PreprocessorState, methodDecl: MethodDec } } +private fun preprocessBlock(state: PreprocessorState, block: Block) { + block.block?.blockStatements + ?.map { blockStmt: BlockStatement -> preprocessBlockStmt(state, blockStmt) } +} + private fun preprocessBlockStmt(state: PreprocessorState, blockStmt: BlockStatement) { blockStmt.declaration?.let { preprocessDecl(state, blockStmt.declaration) @@ -198,8 +209,21 @@ private fun preprocessDecl(state: PreprocessorState, decl: Declaration) { private fun preprocessStmt(state: PreprocessorState, stmt: Statement) { when (stmt) { + is Block -> preprocessBlock(state, stmt) is BlockStatement -> preprocessBlockStmt(state, stmt) is StatementExpression -> preprocessStmtExpr(state, stmt) + is IfThenElse -> { + preprocessStmt(state, stmt.thenPart) + preprocessStmt(state, stmt.elsePart) + } + is While -> { + preprocessExpr(state, stmt.condition) + preprocessStmt(state, stmt.statement) + } + is Do -> { + preprocessExpr(state, stmt.condition) + preprocessStmt(state, stmt.statement) + } else -> { // this is a generated else block } @@ -215,6 +239,11 @@ private fun preprocessVarDecl(state: PreprocessorState, varDecl: VariableDeclara } when (varDecl.type) { is TypeName -> tryAddClassForAliases(state, TokenCodes.EO_CAGE.value, false) + is PrimitiveType -> { + if ((varDecl.type as PrimitiveType).dimensions.dimensions.isNotEmpty()) { + tryAddClassForAliases(state, TokenCodes.EO_CAGE.value, false) + } + } else -> {} } } @@ -262,6 +291,8 @@ private fun preprocessMethodInvocation(state: PreprocessorState, methodInvocatio // this is a generated else block } } + methodInvocation.arguments.arguments + .map { preprocessExpr(state, it) } } private fun preprocessSimpleReference(state: PreprocessorState, ref: SimpleReference) { @@ -283,11 +314,11 @@ private fun preprocessCompoundName(state: PreprocessorState, compoundName: Compo } private fun tryAddClassForAliases(state: PreprocessorState, className: String, forStdLib: Boolean = true) { - if (state.stdTokensNeededForAlias.contains(className)) { + if (state.tokensNeededForAlias.contains(className)) { if (forStdLib) { - state.stdTokensForCurrentAlias.add(className) + state.tokensToImportPath[className]?.let { state.stdTokensForCurrentAlias.add(it) } } else { - state.eoClassesForCurrentAlias.add(className) + state.tokensToImportPath[className]?.let { state.eoClassesForCurrentAlias.add(it) } } } } diff --git a/src/main/java/util/PrimitiveTypesFinder.kt b/src/main/java/util/PrimitiveTypesFinder.kt index d8d01929..7f85f80c 100644 --- a/src/main/java/util/PrimitiveTypesFinder.kt +++ b/src/main/java/util/PrimitiveTypesFinder.kt @@ -22,6 +22,9 @@ import tree.Type.TypeName private fun findPrimitivesInMethodInvocation(primitives: HashSet, methodInvocation: MethodInvocation) { methodInvocation.arguments?.arguments ?.map { findPrimitivesInExpression(primitives, it) } + if (methodInvocation.qualifier != null) { + findPrimitivesInExpression(primitives, methodInvocation.qualifier) + } } private fun decodeLiteralCode(code: TokenCode): TokenCodes? { @@ -42,10 +45,22 @@ private fun findPrimitivesInLiteral(primitives: HashSet, literal: Litera } } +private fun findPrimitivesInSimpleReference(primitives: HashSet, simpleReference: SimpleReference) { + simpleReference.compoundName.names + .map { + run { + if (it.equals("String")) { + primitives.add(TokenCodes.CLASS__STRING.importPath) + } + } + } +} + private fun findPrimitivesInExpression(primitives: HashSet, expr: Expression) { when (expr) { is MethodInvocation -> findPrimitivesInMethodInvocation(primitives, expr) is Literal -> findPrimitivesInLiteral(primitives, expr) + is SimpleReference -> findPrimitivesInSimpleReference(primitives, expr) is Binary -> findPrimitivesInExpression(primitives, expr.right) is Parenthesized -> findPrimitivesInExpression(primitives, expr.expression) is UnaryPrefix -> findPrimitivesInExpression(primitives, expr.operand) From ad1b138adce72c29105316dd721cc11a83480582 Mon Sep 17 00:00:00 2001 From: someilay Date: Wed, 18 May 2022 11:34:41 +0300 Subject: [PATCH 24/29] FEATURE: support of Random & minor fixes --- src/main/java/translator/Declarations.kt | 18 +++++++- src/main/java/translator/MethodInvocations.kt | 4 +- .../translator/preprocessor/Preprocessor.kt | 16 ++++--- src/main/java/util/TokenCodes.kt | 1 + .../resources/stdlib/util/class__Random.eo | 45 +++++++++++++++++++ 5 files changed, 74 insertions(+), 10 deletions(-) create mode 100644 src/main/resources/stdlib/util/class__Random.eo diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index b500f01e..34d29ad6 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -114,7 +114,23 @@ fun mapVariableDeclaration(dec: VariableDeclaration, name: String): List - if (methodQualifier.compoundName.names.size > 1) - methodQualifier.compoundName.names.dropLast(1).eoDot() + if (methodQualifier.compoundName.names.size > 0) + methodQualifier.compoundName.names.eoDot() else "this".eoDot() is FieldAccess -> getFullIdentifier(methodQualifier).eoDot() diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index 308570c2..734493c9 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -37,11 +37,13 @@ data class PreprocessorState( val classNames: HashMap = hashMapOf( "Object" to TokenCodes.CLASS__OBJECT.value, "System" to TokenCodes.CLASS__SYSTEM.value, - "String" to TokenCodes.CLASS__STRING.value + "String" to TokenCodes.CLASS__STRING.value, + "Random" to TokenCodes.CLASS__RANDOM.value ), val tokensNeededForAlias: HashSet = hashSetOf( TokenCodes.CLASS__OBJECT.value, TokenCodes.CLASS__SYSTEM.value, + TokenCodes.CLASS__RANDOM.value, TokenCodes.PRIM__INT.value, TokenCodes.PRIM__FLOAT.value, TokenCodes.PRIM__BOOLEAN.value, @@ -270,7 +272,7 @@ private fun preprocessExpr(state: PreprocessorState, expr: Expression) { private fun preprocessInstanceCreation(state: PreprocessorState, instanceCreation: InstanceCreation) { preprocessType(state, instanceCreation.ctorType) instanceCreation.args.arguments.forEach { preprocessExpr(state, it) } - instanceCreation.classBody.declarations.forEach { preprocessDecl(state, it) } + instanceCreation.classBody?.declarations?.forEach { preprocessDecl(state, it) } } private fun preprocessType(state: PreprocessorState, type: Type) { @@ -300,11 +302,11 @@ private fun preprocessSimpleReference(state: PreprocessorState, ref: SimpleRefer } private fun preprocessCompoundName(state: PreprocessorState, compoundName: CompoundName) { - if (compoundName.names.size == 1 && - state.classNames[compoundName.names.first()] == null - ) { - compoundName.names.add(0, "^") - } +// if (compoundName.names.size == 1 && +// state.classNames[compoundName.names.first()] == null +// ) { +// compoundName.names.add(0, "^") +// } compoundName.names .replaceAll { diff --git a/src/main/java/util/TokenCodes.kt b/src/main/java/util/TokenCodes.kt index af3c8d55..d5edf935 100644 --- a/src/main/java/util/TokenCodes.kt +++ b/src/main/java/util/TokenCodes.kt @@ -13,5 +13,6 @@ enum class TokenCodes(val value: String, val importPath: String) { CLASS__SYSTEM("class__System", "stdlib.lang.class__System"), CLASS__STRING("class__String", "stdlib.lang.class__String"), CLASS__OBJECT("class__Object", "stdlib.lang.class__Object"), + CLASS__RANDOM("class__Random", "stdlib.util.class__Random"), EO_CAGE("gray.cage", "org.eolang.gray.cage") } \ No newline at end of file diff --git a/src/main/resources/stdlib/util/class__Random.eo b/src/main/resources/stdlib/util/class__Random.eo new file mode 100644 index 00000000..a6ab283d --- /dev/null +++ b/src/main/resources/stdlib/util/class__Random.eo @@ -0,0 +1,45 @@ ++package stdlib.util ++alias stdlib.lang.class__Object ++alias stdlib.primitives.prim__int ++alias stdlib.primitives.prim__float + +[] > class__Random + class__Object > super + super > @ + + [] > new + [] > this + class__Object.new > super + super > @ + "class__Random" > className + + [this] > init + 0 > @ + + [this] > nextInt + random > r + seq > @ + prim__int.constructor_2 + prim__int.new + as-int. + sub. + mul. + 4294967295.0 + r + 2147483648.0 + + [this] > nextFloat + random > r + seq > @ + prim__float.constructor_2 + prim__float.new + r + + seq > @ + this + + [this] > constructor + seq > @ + this.init + this + this From 90f2ec90af070e35bed1a9580ffc65f62ce09f81 Mon Sep 17 00:00:00 2001 From: someilay Date: Thu, 19 May 2022 22:05:11 +0300 Subject: [PATCH 25/29] FEATURE: support of explicit conversions & minor fixes --- src/main/java/parser/TreeMappings.kt | 13 ++++- src/main/java/translator/Expressions.kt | 40 +++++++++++++-- .../translator/preprocessor/Preprocessor.kt | 35 ++++++++++--- src/main/java/util/PrimitiveTypesFinder.kt | 51 +++++++++++++++---- .../resources/stdlib/primitives/prim__int.eo | 18 +++---- .../resources/stdlib/primitives/prim__num.eo | 36 +++++++++++++ 6 files changed, 158 insertions(+), 35 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index bd5cb1e8..46158732 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -290,14 +290,23 @@ fun ExpressionContext.toArrayAccess(): ArrayAccess? { return null } +fun ExpressionContext.toCastExpr(): Cast? { + val typeList = typeType() + val expr = expression(0) + if (LPAREN() != null && RPAREN() != null && typeList.isNotEmpty() && expr != null) { + return Cast(TypeList(typeList[0].toType()), expr.toExpression()) + } + return null +} + fun ExpressionContext.toExpression(): Expression { val expr0 = - this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: expression(0)?.toExpression() + this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: this.toCastExpr() ?: expression(0)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() ?: creator()?.toExpression() ?: methodCall()?.toExpression(null) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ if (this.bop != null) { val expr1 = - this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: expression(1)?.toExpression() + this.toArrayAccess() ?: this.toUnaryPrefixPostfix() ?: this.toCastExpr() ?: expression(1)?.toExpression() ?: primary()?.toExpression() ?: identifier()?.toExpression() ?: creator()?.toExpression() ?: methodCall()?.toExpression(expr0) ?: SimpleReference(CompoundName("expression_placeholder")) /* FIXME */ diff --git a/src/main/java/translator/Expressions.kt b/src/main/java/translator/Expressions.kt index 188c6369..402eef9b 100644 --- a/src/main/java/translator/Expressions.kt +++ b/src/main/java/translator/Expressions.kt @@ -4,12 +4,10 @@ import arrow.core.None import arrow.core.flatten import eotree.* import lexer.TokenCode -import tree.Expression.Binary -import tree.Expression.Expression +import tree.Expression.* import tree.Expression.Primary.* -import tree.Expression.SimpleReference -import tree.Expression.UnaryPostfix -import tree.Expression.UnaryPrefix +import tree.Type.PrimitiveType +import tree.Type.TypeName fun mapExpression(expr: Expression, name: String): List = when (expr) { @@ -37,6 +35,8 @@ fun mapExpression(expr: Expression, name: String): List = mapArrayCreation(expr, name) is ArrayAccess -> mapArrayAccess(expr, name) + is Cast -> + mapCastExpr(expr, name) else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } @@ -67,10 +67,40 @@ fun constructExprName(expr: Expression): String = "a_c${expr.hashCode()}" is ArrayAccess -> "a_a${expr.hashCode()}" + is Cast -> + "c${expr.hashCode()}" else -> throw IllegalArgumentException("Expression of type ${expr.javaClass.simpleName} is not supported") } +fun mapCastExpr(cast: Cast, name: String): List { + val castType = cast.types.types[0] + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + (when(castType) { + is PrimitiveType -> listOf(decodePrimitiveType(castType).value) + is TypeName -> castType.compoundName.names + else -> listOf("unknown_type_${castType.javaClass.simpleName}") + } + + listOf("from") + ).eoDot(), + constructExprName(cast.expression).eoDot() + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(cast.expression, constructExprName(cast.expression)) +} + fun mapArrayAccess(access: ArrayAccess, name: String): List { return listOf( EOBndExpr( diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index 734493c9..cff7820b 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -6,11 +6,15 @@ import tree.Compilation.SimpleCompilationUnit import tree.Compilation.TopLevelComponent import tree.CompoundName import tree.Declaration.* +import tree.Expression.Cast import tree.Expression.Expression import tree.Expression.Primary.FieldAccess import tree.Expression.Primary.InstanceCreation import tree.Expression.Primary.MethodInvocation +import tree.Expression.Primary.Parenthesized import tree.Expression.SimpleReference +import tree.Initializer +import tree.InitializerArray import tree.InitializerSimple import tree.Statement.Block import tree.Statement.BlockStatement @@ -233,14 +237,12 @@ private fun preprocessStmt(state: PreprocessorState, stmt: Statement) { } private fun preprocessVarDecl(state: PreprocessorState, varDecl: VariableDeclaration) { - when (varDecl.initializer) { - is InitializerSimple -> preprocessSimpleInitializer(state, varDecl.initializer as InitializerSimple) - else -> { - // this is a generated else block - } - } + preprocessInitializer(state, varDecl.initializer) when (varDecl.type) { - is TypeName -> tryAddClassForAliases(state, TokenCodes.EO_CAGE.value, false) + is TypeName -> { + preprocessType(state, varDecl.type) + tryAddClassForAliases(state, TokenCodes.EO_CAGE.value, false) + } is PrimitiveType -> { if ((varDecl.type as PrimitiveType).dimensions.dimensions.isNotEmpty()) { tryAddClassForAliases(state, TokenCodes.EO_CAGE.value, false) @@ -250,6 +252,17 @@ private fun preprocessVarDecl(state: PreprocessorState, varDecl: VariableDeclara } } +private fun preprocessInitializer(state: PreprocessorState, initializer: Initializer) { + when (initializer) { + is InitializerSimple -> preprocessSimpleInitializer(state, initializer) + is InitializerArray -> initializer.initializers + .map { preprocessInitializer(state, initializer) } + else -> { + // this is a generated else block + } + } +} + private fun preprocessSimpleInitializer(state: PreprocessorState, initializer: InitializerSimple) { preprocessExpr(state, initializer.expression) } @@ -263,12 +276,20 @@ private fun preprocessExpr(state: PreprocessorState, expr: Expression) { is SimpleReference -> preprocessSimpleReference(state, expr) is MethodInvocation -> preprocessMethodInvocation(state, expr) is InstanceCreation -> preprocessInstanceCreation(state, expr) + is Cast -> preprocessCastExpr(state, expr) + is Parenthesized -> preprocessExpr(state, expr.expression) else -> { // this is a generated else block } } } +private fun preprocessCastExpr(state: PreprocessorState, cast: Cast) { + preprocessExpr(state, cast.expression) + cast.types.types + .map { preprocessType(state, it) } +} + private fun preprocessInstanceCreation(state: PreprocessorState, instanceCreation: InstanceCreation) { preprocessType(state, instanceCreation.ctorType) instanceCreation.args.arguments.forEach { preprocessExpr(state, it) } diff --git a/src/main/java/util/PrimitiveTypesFinder.kt b/src/main/java/util/PrimitiveTypesFinder.kt index 7f85f80c..d5138542 100644 --- a/src/main/java/util/PrimitiveTypesFinder.kt +++ b/src/main/java/util/PrimitiveTypesFinder.kt @@ -12,6 +12,9 @@ import tree.Expression.* import tree.Expression.Primary.Literal import tree.Expression.Primary.MethodInvocation import tree.Expression.Primary.Parenthesized +import tree.Initializer +import tree.InitializerArray +import tree.InitializerSimple import tree.Statement.BlockStatement import tree.Statement.Statement import tree.Statement.StatementExpression @@ -28,7 +31,7 @@ private fun findPrimitivesInMethodInvocation(primitives: HashSet, method } private fun decodeLiteralCode(code: TokenCode): TokenCodes? { - return when(code) { + return when (code) { TokenCode.IntegerLiteral -> TokenCodes.PRIM__INT TokenCode.FloatingLiteral -> TokenCodes.PRIM__FLOAT TokenCode.StringLiteral -> TokenCodes.CLASS__STRING @@ -56,11 +59,31 @@ private fun findPrimitivesInSimpleReference(primitives: HashSet, simpleR } } +private fun findPrimitivesInType(primitives: HashSet, type: Type) { + when (type) { + is PrimitiveType -> primitives.add(decodePrimitiveType(type).importPath) + is TypeName -> { + if (type.compoundName.names.size == 1 && + type.compoundName.names.last().equals("String") + ) { + primitives.add(TokenCodes.CLASS__STRING.importPath) + } + } + } +} + +private fun findPrimitivesInCastExpr(primitives: HashSet, cast: Cast) { + cast.types.types + .map { findPrimitivesInType(primitives, it) } + findPrimitivesInExpression(primitives, cast.expression) +} + private fun findPrimitivesInExpression(primitives: HashSet, expr: Expression) { when (expr) { is MethodInvocation -> findPrimitivesInMethodInvocation(primitives, expr) is Literal -> findPrimitivesInLiteral(primitives, expr) is SimpleReference -> findPrimitivesInSimpleReference(primitives, expr) + is Cast -> findPrimitivesInCastExpr(primitives, expr) is Binary -> findPrimitivesInExpression(primitives, expr.right) is Parenthesized -> findPrimitivesInExpression(primitives, expr.expression) is UnaryPrefix -> findPrimitivesInExpression(primitives, expr.operand) @@ -69,7 +92,7 @@ private fun findPrimitivesInExpression(primitives: HashSet, expr: Expres } private fun findPrimitivesInStatement(primitives: HashSet, stmt: Statement) { - when(stmt) { + when (stmt) { is StatementExpression -> findPrimitivesInExpression(primitives, stmt.expression) } } @@ -89,14 +112,24 @@ private fun findPrimitivesInMethod(primitives: HashSet, methodDecl: Meth ?.map { findPrimitivesInBlockStmt(primitives, it) } } -private fun findPrimitivesInVarDeclaration(primitives: HashSet, varDeclType: Type) { - if (varDeclType is PrimitiveType) { - primitives.add(decodePrimitiveType(varDeclType).importPath) - } else if (varDeclType is TypeName && - varDeclType.compoundName.names.size == 1 && - varDeclType.compoundName.names.last().equals("String")) { +private fun findPrimitivesInInitializer(primitives: HashSet, initializer: Initializer) { + when (initializer) { + is InitializerSimple -> findPrimitivesInExpression(primitives, initializer.expression) + is InitializerArray -> initializer.initializers + .map { findPrimitivesInInitializer(primitives, it) } + } +} + +private fun findPrimitivesInVarDeclaration(primitives: HashSet, dec: VariableDeclaration) { + if (dec.type is PrimitiveType) { + primitives.add(decodePrimitiveType(dec.type as PrimitiveType).importPath) + } else if (dec.type is TypeName && + (dec.type as TypeName).compoundName.names.size == 1 && + (dec.type as TypeName).compoundName.names.last().equals("String") + ) { primitives.add(TokenCodes.CLASS__STRING.importPath) } + findPrimitivesInInitializer(primitives, dec.initializer) } private fun findPrimitivesInClass(primitives: HashSet, clsDec: NormalClassDeclaration) { @@ -107,7 +140,7 @@ private fun findPrimitivesInClass(primitives: HashSet, clsDec: NormalCla private fun findPrimitivesInDeclaration(primitives: HashSet, dec: Declaration) { when (dec) { is NormalClassDeclaration -> findPrimitivesInClass(primitives, dec) - is VariableDeclaration -> findPrimitivesInVarDeclaration(primitives, dec.type) + is VariableDeclaration -> findPrimitivesInVarDeclaration(primitives, dec) is MethodDeclaration -> findPrimitivesInMethod(primitives, dec) } } diff --git a/src/main/resources/stdlib/primitives/prim__int.eo b/src/main/resources/stdlib/primitives/prim__int.eo index b76af4a9..8f5ba65f 100644 --- a/src/main/resources/stdlib/primitives/prim__int.eo +++ b/src/main/resources/stdlib/primitives/prim__int.eo @@ -102,18 +102,12 @@ [right] > from seq > @ - if. - or. - right.prim_name.eq "prim__float" - right.prim_name.eq "prim__double" - prim__int.constructor_2 - prim__int.new - right.v.as-int.mod - max_int - prim__int.constructor_2 - prim__int.new - right.v.mod - max_int + prim__int.constructor_2 + prim__int.new + mod. + right.integer_part + right + max_int [this] > constructor_1 seq > @ diff --git a/src/main/resources/stdlib/primitives/prim__num.eo b/src/main/resources/stdlib/primitives/prim__num.eo index f66246a7..b978a934 100644 --- a/src/main/resources/stdlib/primitives/prim__num.eo +++ b/src/main/resources/stdlib/primitives/prim__num.eo @@ -12,6 +12,42 @@ seq > @ ^.v.as-string + [this] > integer_part + seq > @ + if. + not. + this.prim_name.eq "prim__boolean" + if. + and. + not. + this.prim_name.eq "prim__float" + not. + this.prim_name.eq "prim__double" + this.v + this.v.as-int + if. + this.v + 1 + 0 + + [this] > float_part + seq > @ + if. + not. + this.prim_name.eq "prim__boolean" + if. + and. + not. + this.prim_name.eq "prim__float" + not. + this.prim_name.eq "prim__double" + this.v.as-float + this.v + if. + this.v + 1.0 + 0.0 + [this value] > init seq > @ this.v.write From 8dcb1c8bb621f9e1457d3fa0eab7eb0ca18e8051 Mon Sep 17 00:00:00 2001 From: someilay Date: Sat, 21 May 2022 23:35:45 +0300 Subject: [PATCH 26/29] FEATURE: support of nested classes FEATURE: support of constructors FEATURE: support of asserts FIXES: method modifiers are again supported & minor fixes --- src/main/java/parser/JavaParser.java | 12 +++ src/main/java/parser/TreeMappings.kt | 91 +++++++++++++++++-- src/main/java/translator/Blocks.kt | 22 ++++- src/main/java/translator/Classes.kt | 7 +- src/main/java/translator/Declarations.kt | 78 ++++++++-------- src/main/java/translator/MethodInvocations.kt | 17 +++- src/main/java/translator/Methods.kt | 70 ++++++-------- src/main/java/translator/Statements.kt | 45 ++++++++- src/main/java/translator/Translator.kt | 11 ++- .../translator/preprocessor/Preprocessor.kt | 45 +++++++-- src/main/java/util/MainFinder.kt | 32 +++---- src/main/java/util/NewGenerator.kt | 68 ++++++++++++-- src/main/java/util/PrimitiveTypesFinder.kt | 11 ++- src/main/java/util/StaticGenerator.kt | 21 ++--- 14 files changed, 378 insertions(+), 152 deletions(-) diff --git a/src/main/java/parser/JavaParser.java b/src/main/java/parser/JavaParser.java index 492a1831..e3f00c24 100644 --- a/src/main/java/parser/JavaParser.java +++ b/src/main/java/parser/JavaParser.java @@ -751,6 +751,18 @@ public AnnotationContext annotation() { public TerminalNode STRICTFP() { return getToken(JavaParser.STRICTFP, 0); } public TerminalNode SEALED() { return getToken(JavaParser.SEALED, 0); } public TerminalNode NON_SEALED() { return getToken(JavaParser.NON_SEALED, 0); } + public TerminalNode terminalNode(int i) { + int j = -1; + for (ParseTree o : children) { + if ( o instanceof TerminalNode ) { + j++; + if (i == j) { + return (TerminalNode) o; + } + } + } + return null; + } public ClassOrInterfaceModifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 46158732..a498e62c 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -15,7 +15,6 @@ import tree.Expression.* import tree.Expression.Primary.* import tree.Statement.* import tree.Type.* -import kotlin.reflect.typeOf fun CompilationUnitContext.toCompilationUnit(): CompilationUnit { val imports = ArrayList(importDeclaration().map { it.toImportDeclaration() }) @@ -51,24 +50,92 @@ fun ClassDeclarationContext.toClassDeclaration(): ClassDeclaration = ) fun ClassBodyContext.toDeclarations(): Declarations { - val clsBodyDecls = ArrayList(this.classBodyDeclaration().mapNotNull { it.toDeclaration() }) + val clsBodyDecls = ArrayList( + this.classBodyDeclaration().mapNotNull { it.toDeclaration() }.flatten() + ) val decls = Declarations(clsBodyDecls.removeFirstOrNull()) clsBodyDecls.forEach { decls.add(it) } decls.declarations.removeIf { it == null } return decls } -fun ClassBodyDeclarationContext.toDeclaration(): Declaration? = +fun ClassBodyDeclarationContext.toDeclaration(): List? = memberDeclaration()?.toDeclaration(modifier()) ?: block()?.toDeclaration(STATIC()) -fun MemberDeclarationContext.toDeclaration(modifiers: List?): Declaration? = - methodDeclaration()?.toDeclaration() +fun MemberDeclarationContext.toDeclaration(modifiers: List?): List? = + if (methodDeclaration() != null) { listOf(methodDeclaration().toDeclaration(modifiers)) } else { null } ?: + if (classDeclaration() != null) { listOf(classDeclaration().toClassDeclaration()) } else { null } ?: + fieldDeclaration()?.toDeclaration(modifiers) ?: + if (constructorDeclaration() != null) { listOf(constructorDeclaration().toDeclaration(modifiers)) } else { null } // FIXME: support other declarations -fun MethodDeclarationContext.toDeclaration(): Declaration = +fun ConstructorDeclarationContext.toDeclaration(modifiers: List?): Declaration { + val excsTypes = qualifiedNameList()?.qualifiedName()?.map { TypeName(it.toCompoundName(), null) } + + var excsTypeList: TypeList? = null + if (excsTypes != null) { + excsTypeList = TypeList(null) + excsTypeList.types = ArrayList(excsTypes) + } + + return ConstructorDeclaration( + modifiers.getModifiers(), + null, + formalParameters().toParameterDeclarations(), + excsTypeList, + null, /* FIXME (WHY DO WE SHOULD EXPLICIT DISTINGUISH SUPER CALL?) */ + constructorBody.toBlock() + ) +} + +fun FieldDeclarationContext.toDeclaration(modifiers: List?): List { + val variableDeclarators = variableDeclarators().toVariableDeclarators() + val type = typeType()?.toType() + val trueModifiers = modifiers.getModifiers() + return variableDeclarators.declarators + .map { + VariableDeclaration( + it.name, + trueModifiers, + type, + it.dims, + it.initializer + ) + } +} + +fun TerminalNode.toTypeModifier(): TokenCode? { + return when(symbol.type) { + PUBLIC -> TokenCode.Public + PRIVATE -> TokenCode.Private + STATIC -> TokenCode.Static + PROTECTED -> TokenCode.Protected + ABSTRACT -> TokenCode.Abstract + FINAL -> TokenCode.Final + STRICTFP -> TokenCode.Strictfp + else -> null + } +} + +fun List?.getModifiers(): Modifiers? { + if (this == null) { + return null + } + val tokenModifiers = mapNotNull { it.classOrInterfaceModifier()?.terminalNode(0)?.toTypeModifier() } + if (tokenModifiers.isNotEmpty()) { + val standardModifiers = StandardModifiers(Token(tokenModifiers[0])) + for (i in 1 until tokenModifiers.size) { + standardModifiers.add(Token(tokenModifiers[i])) + } + return Modifiers(null, standardModifiers) + } + return null +} + +fun MethodDeclarationContext.toDeclaration(modifiers: List?): Declaration = MethodDeclaration( - null /* FIXME */, + modifiers.getModifiers(), null /* FIXME */, typeTypeOrVoid().toType() /* FIXME */, identifier().text /* FIXME */, @@ -110,8 +177,8 @@ fun FormalParameterContext.toParameterDeclaration(): ParameterDeclaration = fun TypeTypeOrVoidContext.toType(): Type? = typeType()?.toType() -fun BlockContext.toDeclaration(isStatic: TerminalNode?): Declaration = - ClassInitializer(this.toBlock(), isStatic != null) +fun BlockContext.toDeclaration(isStatic: TerminalNode?): List = + listOf(ClassInitializer(this.toBlock(), isStatic != null)) fun BlockContext.toBlock(): Block { val blockStmntsLst = ArrayList(this.blockStatement().map { it.toBlockStatement() }) @@ -386,11 +453,15 @@ fun MethodCallContext.toExpression(expr: Expression?): Expression { val argList = ArgumentList(exprLst.removeFirstOrNull()) exprLst.forEach { argList.add(it) } argList.arguments.removeIf { it == null } + val t = THIS() return MethodInvocation( expr, SUPER() != null, null, // TODO: type arguments are somewhere else - identifier().toToken(), + identifier()?.toToken() ?: + if (SUPER() != null) {Token(TokenCode.Super, "super")} else { null } ?: + if (THIS() != null) {Token(TokenCode.This, "this")} else { null }, + /* FIXME (SHOULD BE IMPLEMENTED IN ANOTHER WAY) */ argList ) } diff --git a/src/main/java/translator/Blocks.kt b/src/main/java/translator/Blocks.kt index b62aa2f9..33a3b08f 100644 --- a/src/main/java/translator/Blocks.kt +++ b/src/main/java/translator/Blocks.kt @@ -12,14 +12,16 @@ import tree.Statement.BlockStatement * In order to map Java block into EO, all variable declarations are separated out as memory objects and then seq * contains all the logic. */ -fun mapBlock(block: Block, name: String? = null): List { +fun mapBlock(block: Block, + name: String? = null, + additionalStmt: Pair>? = null): List { if (name != null) { return listOf( EOBndExpr( EOObject( listOf(), None, - mapBlock(block) + mapBlock(block, additionalStmt = additionalStmt) ), name ) @@ -33,14 +35,24 @@ fun mapBlock(block: Block, name: String? = null): List { EOBndExpr( EOCopy( "seq", + if (additionalStmt != null) { + listOf(additionalStmt.first.eoDot()) + } else { + listOf() + } + if (parsedStatements.isNotEmpty()) parsedStatements.keys.map { it.eoDot() } - else - listOf("0".eoDot()) + else { + if (additionalStmt == null) { + listOf("TRUE".eoDot()) + } else { + listOf() + } + } ), "@" ) - ) + parsedStatements.values.toList().flatten() + ) + (additionalStmt?.second ?: listOf()) + parsedStatements.values.toList().flatten() } diff --git a/src/main/java/translator/Classes.kt b/src/main/java/translator/Classes.kt index 69c8fa6a..961e1891 100644 --- a/src/main/java/translator/Classes.kt +++ b/src/main/java/translator/Classes.kt @@ -4,6 +4,7 @@ import arrow.core.None import eotree.EOBnd import eotree.EOBndExpr import eotree.EOObject +import eotree.data.EOStringData import eotree.eoDot import tree.Declaration.ClassDeclaration import tree.Declaration.InterfaceDeclaration @@ -51,9 +52,9 @@ fun mapClass(clsDec: ClassDeclaration): EOBndExpr { ) + (generateNew(clsDec)) + generateStatic(clsDec) - + clsDec.body.declarations - .filterIsInstance() - .map { mapClass(it) } +// + clsDec.body.declarations +// .filterIsInstance() +// .map { mapClass(it) } ), clsDec.name ) diff --git a/src/main/java/translator/Declarations.kt b/src/main/java/translator/Declarations.kt index 34d29ad6..0f4554ff 100644 --- a/src/main/java/translator/Declarations.kt +++ b/src/main/java/translator/Declarations.kt @@ -27,7 +27,7 @@ fun mapClassDeclaration(dec: Declaration): List { listOf(mapClass(dec as ClassDeclaration)) } is VariableDeclaration -> { - mapVariableDeclaration(dec, "n") + mapVariableDeclaration(dec, "dec", false) } else -> { listOf() @@ -52,7 +52,7 @@ fun mapDeclaration(dec: Declaration, name: String): List { } } -fun mapVariableDeclaration(dec: VariableDeclaration, name: String): List = +fun mapVariableDeclaration(dec: VariableDeclaration, name: String, mapInitializer: Boolean = true): List = when (dec.type) { is TypeName -> { listOf( @@ -93,45 +93,47 @@ fun mapVariableDeclaration(dec: VariableDeclaration, name: String): List throw IllegalArgumentException("Type of type " + dec.type.javaClass.name + " is not supported") - } + if (dec.initializer != null) { - listOf( - EOBndExpr( - EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - listOf(dec.name, "write").eoDot(), - constructInitName(dec.initializer).eoDot() - ), - "@" + } + if (mapInitializer) { + if (dec.initializer != null) { + listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(dec.name, "write").eoDot(), + constructInitName(dec.initializer).eoDot() + ), + "@" + ) ) - ) - ), - name - ) - ) + - mapInitializer(dec.initializer, constructInitName(dec.initializer)) - } else { - listOf( - EOBndExpr( - EOObject( - listOf(), - None, - listOf( - EOBndExpr( - EOCopy( - "TRUE" - ), - "@" + ), + name + ) + ) + + mapInitializer(dec.initializer, constructInitName(dec.initializer)) + } else { + listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + "TRUE" + ), + "@" + ) ) - ) - ), - name + ), + name + ) ) - ) - } + } + } else { listOf() } fun decodePrimitiveType(type: PrimitiveType): TokenCodes { return when (type.typeCode) { diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index b7f8bbb4..0a2886cf 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -43,18 +43,27 @@ private fun getFullIdentifier(fieldAccess: FieldAccess): List { ) + listOf(fieldAccess.identifier) } +fun trueMethodInvocationName(name: String): List { + return when (name) { + "this" -> listOf("constructor") /* FIXME (IT'S NOT ALWAYS TRUE) */ + "super" -> listOf("super", "constructor") /* FIXME (IT'S NOT ALWAYS TRUE) */ + else -> listOf(name) + } +} // TODO: create state object to store binding of expression fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List { - require(!methodInvocation.superSign) { "Super sign isn't supported yet" } + // require(!methodInvocation.superSign) { "Super sign isn't supported yet" } + /* FIXME (NOW PARTIALLY SUPPORTED) */ require(methodInvocation.typeArguments == null) { "Type arguments aren't supported yet" } val isStaticCall = isStaticCall(methodInvocation) + val trueName = trueMethodInvocationName(methodInvocation.name) val src: EODot = when (val methodQualifier = methodInvocation.qualifier) { - is SimpleReference -> (methodQualifier.compoundName.names + listOf(methodInvocation.name)).eoDot() - is FieldAccess -> (getFullIdentifier(methodQualifier) + listOf(methodInvocation.name)).eoDot() - null -> methodInvocation.name.eoDot() + is SimpleReference -> (methodQualifier.compoundName.names + trueName).eoDot() + is FieldAccess -> (getFullIdentifier(methodQualifier) + trueName).eoDot() + null -> trueName.eoDot() else -> throw IllegalArgumentException("Unsupported method qualifier!") } diff --git a/src/main/java/translator/Methods.kt b/src/main/java/translator/Methods.kt index 49dde7e3..35b1b823 100644 --- a/src/main/java/translator/Methods.kt +++ b/src/main/java/translator/Methods.kt @@ -6,15 +6,9 @@ import eotree.EOCopy import eotree.EOObject import eotree.eoDot import lexer.TokenCode +import tree.Declaration.ConstructorDeclaration import tree.Declaration.MethodDeclaration import tree.Declaration.ParameterDeclaration -import tree.Declaration.VariableDeclaration -import tree.Entity -import tree.Expression.Expression -import tree.Initializer -import tree.Statement.BlockStatements -import util.ParseExprTasks -import kotlin.collections.flatten // fun MethodDeclaration.getLocalVariables(): List = // // TODO: add support for nested block variables as well @@ -26,7 +20,6 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { val isStatic = dec.modifiers != null && dec.modifiers.modifiers.modifiers.find { it == TokenCode.Static } != null val additionalParameters = if (!isStatic) listOf("this") else ArrayList() - val parseExprTasks = ParseExprTasks() val obj = EOObject( // Non-vararg parameters @@ -51,12 +44,37 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { // Bound attributes if (dec.methodBody != null) { - mapBlock(dec.methodBody) + mapBlock( + dec.methodBody, + additionalStmt = if (dec is ConstructorDeclaration) { + "initialization" to listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf("this", "init").eoDot(), + "this".eoDot() + ), + "@" + ) + ) + ), + "initialization" + ) + + ) + } else { + null + } + ) } else { listOf( EOBndExpr( EOCopy( - "0", + "TRUE", ArrayList() ), "@" @@ -87,36 +105,6 @@ fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { return EOBndExpr( obj, - dec.name + dec.name ?: "constructor" ) } - -//fun parseExprTasks(parseExprTasks: ParseExprTasks): List { -// return if (parseExprTasks.tasks.size > 0) { -// parseExprTasks.tasks -// .map { parseExprTask(it.second, it.first) } -// .flatten() -// } else { -// listOf() -// } -//} -// -//fun parseExprTask(e: Entity, name: String): List { -// val parseExprTasks = ParseExprTasks() -// return when (e) { -// is Expression -> { -// listOf(EOBndExpr(mapExpression(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) -// } -// is Initializer -> { -// listOf(EOBndExpr(mapInitializer(parseExprTasks, e), name)) + parseExprTasks(parseExprTasks) -// } -// else -> { -// throw IllegalArgumentException("Entity of type ${e.javaClass.simpleName} cannot be parsed") -// } -// } -//} -// -//fun BlockStatements.findAllLocalVariables(): List = -// blockStatements -// .filter { it.declaration is VariableDeclaration } -// .map { it.declaration as VariableDeclaration } diff --git a/src/main/java/translator/Statements.kt b/src/main/java/translator/Statements.kt index 05a12750..904af54d 100644 --- a/src/main/java/translator/Statements.kt +++ b/src/main/java/translator/Statements.kt @@ -29,6 +29,7 @@ fun mapStatement(statement: Statement, name: String): List = is Do -> mapDoStatement(statement, name) is Block -> mapBlock(statement, name) // is Switch -> mapSwitchStatement(parseExprTasks, statement) + is Assert -> mapAssert(statement, name) else -> listOf() // FIXME // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") @@ -42,7 +43,7 @@ fun mapEmptyStmt(name: String) : EOBndExpr = listOf( EOBndExpr( EOCopy( - "0".eoDot() + "0" ), "@" ) @@ -60,12 +61,54 @@ fun constructStmtName(statement: Statement): String = is Do -> "do${statement.hashCode()}" is Block -> "b${statement.hashCode()}" // is Switch -> mapSwitchStatement(parseExprTasks, statement) + is Assert -> "ast${statement.hashCode()}" else -> "unknown${statement.hashCode()}" // FIXME // FIXME: throw IllegalArgumentException("Statement of type ${statement.javaClass.simpleName} is not supported") } +fun mapAssert(assert: Assert, name: String): List { + return listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf(constructExprName(assert.expression), "if").eoDot(), + "TRUE".eoDot(), + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + if (assert.expression2 == null) { + "\"AssertionError\"".eoDot() + } else { + constructExprName(assert.expression2).eoDot() + } + ), + "msg" + ) + ) + ), + ), + "@" + ) + ) + ), + name + ) + ) + mapExpression(assert.expression, constructExprName(assert.expression)) + if (assert.expression2 != null) { + mapExpression(assert.expression2, constructExprName(assert.expression2)) + } else { + listOf() + } +} + fun mapStatementExpression(stmtExpr: StatementExpression, name: String): List { return mapExpression(stmtExpr.expression, name) } diff --git a/src/main/java/translator/Translator.kt b/src/main/java/translator/Translator.kt index d313ac6c..a9a806c0 100644 --- a/src/main/java/translator/Translator.kt +++ b/src/main/java/translator/Translator.kt @@ -11,6 +11,7 @@ import tree.Compilation.SimpleCompilationUnit import tree.Compilation.TopLevelComponent import util.findMainClass import util.generateEntryPoint +import util.logger import java.time.LocalDateTime import java.util.* @@ -50,12 +51,12 @@ class Translator { // FIXME: assuming there is only one top-level component and it is a class + val mainClassName = findMainClass(unit) var entrypointBnds = listOf() - try { - val mainClassName = findMainClass(unit) + if (mainClassName != null) { entrypointBnds = generateEntryPoint(mainClassName) - } catch (e: NullPointerException) { - // FIXME: logger.info { "No entry point here!" } + } else { + logger.info { "No entry point here!" } } // FIXME: assuming there is only one top-level component and it is a class @@ -79,7 +80,7 @@ class Translator { ) } - fun mapTopLevelComponent(component: TopLevelComponent): EOBnd { + private fun mapTopLevelComponent(component: TopLevelComponent): EOBnd { return if (component.classDecl != null) { mapClass(component.classDecl) } else if (component.interfaceDecl != null) { diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index cff7820b..cb18045e 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -1,11 +1,13 @@ package translator.preprocessor +import lexer.Token import lexer.TokenCode import tree.Compilation.CompilationUnit import tree.Compilation.SimpleCompilationUnit import tree.Compilation.TopLevelComponent import tree.CompoundName import tree.Declaration.* +import tree.Expression.ArgumentList import tree.Expression.Cast import tree.Expression.Expression import tree.Expression.Primary.FieldAccess @@ -16,13 +18,7 @@ import tree.Expression.SimpleReference import tree.Initializer import tree.InitializerArray import tree.InitializerSimple -import tree.Statement.Block -import tree.Statement.BlockStatement -import tree.Statement.Do -import tree.Statement.IfThenElse -import tree.Statement.Statement -import tree.Statement.StatementExpression -import tree.Statement.While +import tree.Statement.* import tree.Type.PrimitiveType import tree.Type.Type import tree.Type.TypeName @@ -166,6 +162,35 @@ private fun preprocessClassDecl(state: PreprocessorState, clsDec: ClassDeclarati } catch (e: NullPointerException) { /* Ignore it */ } + tryToAddConstructor(clsDec) +} + +private fun tryToAddConstructor(clsDec: NormalClassDeclaration) { + if (clsDec.body?.declarations?.find { it is ConstructorDeclaration } == null) { + val argList = ArgumentList(null) + argList.arguments = ArrayList() + val genConstDecl = ConstructorDeclaration( + null, null, null, null, null, + Block( + ArrayList(), + BlockStatements( + BlockStatement( + StatementExpression( + ArrayList(), + MethodInvocation( + null, true, null, Token(TokenCode.Super, "super"), argList + ) + ) + ) + ) + ) + ) + if (clsDec.body != null) { + clsDec.body.add(genConstDecl) + } else { + clsDec.body = Declarations(genConstDecl) + } + } } private fun preprocessMethodDecl(state: PreprocessorState, methodDecl: MethodDeclaration) { @@ -218,6 +243,12 @@ private fun preprocessStmt(state: PreprocessorState, stmt: Statement) { is Block -> preprocessBlock(state, stmt) is BlockStatement -> preprocessBlockStmt(state, stmt) is StatementExpression -> preprocessStmtExpr(state, stmt) + is Assert -> { + preprocessExpr(state, stmt.expression) + if (stmt.expression2 != null) { + preprocessExpr(state, stmt.expression2) + } + } is IfThenElse -> { preprocessStmt(state, stmt.thenPart) preprocessStmt(state, stmt.elsePart) diff --git a/src/main/java/util/MainFinder.kt b/src/main/java/util/MainFinder.kt index a3b13506..702ab9b4 100644 --- a/src/main/java/util/MainFinder.kt +++ b/src/main/java/util/MainFinder.kt @@ -9,29 +9,21 @@ import tree.Declaration.NormalClassDeclaration fun containsMain(component: TopLevelComponent): Boolean { return if (component.classDecl != null) { - try { - (component.classDecl as NormalClassDeclaration).body.declarations - .filterIsInstance() - .find { declaration: Declaration? -> - try { - (declaration as MethodDeclaration).parameters.parameters.size == 1 && - declaration.parameters.parameters[0].name == "args" && - declaration.name == "main" && - declaration.modifiers.modifiers.modifiers.size == 2 && - declaration.modifiers.modifiers.modifiers.find { it == TokenCode.Static } != null && - declaration.modifiers.modifiers.modifiers.find { it == TokenCode.Public } != null - } catch (e: NullPointerException) { - false - } - } != null - } catch (e: NullPointerException) { - false - } + (component.classDecl as NormalClassDeclaration).body?.declarations + ?.filterIsInstance() + ?.find { declaration: Declaration? -> + (declaration as MethodDeclaration).parameters?.parameters?.size == 1 && + declaration.parameters?.parameters?.get(0)?.name == "args" && + declaration.name == "main" && + declaration.modifiers?.modifiers?.modifiers?.size == 2 && + declaration.modifiers?.modifiers?.modifiers?.find { it == TokenCode.Static } != null && + declaration.modifiers?.modifiers?.modifiers?.find { it == TokenCode.Public } != null + } != null } else { false } } -fun findMainClass(unit: SimpleCompilationUnit): String { - return unit.components.components.find { component: TopLevelComponent -> containsMain(component) }!!.classDecl.name +fun findMainClass(unit: SimpleCompilationUnit): String? { + return unit.components.components.find { component: TopLevelComponent -> containsMain(component) }?.classDecl?.name } diff --git a/src/main/java/util/NewGenerator.kt b/src/main/java/util/NewGenerator.kt index 38219240..39dadd56 100644 --- a/src/main/java/util/NewGenerator.kt +++ b/src/main/java/util/NewGenerator.kt @@ -6,14 +6,64 @@ import arrow.core.flattenOption import eotree.EOBndExpr import eotree.EOCopy import eotree.EOObject +import eotree.data.EOStringData import eotree.eoDot import lexer.TokenCode -import translator.mapClassDeclaration +import translator.* import tree.CompoundName -import tree.Declaration.Declaration -import tree.Declaration.NormalClassDeclaration +import tree.Declaration.* import tree.Type.TypeName +fun generateInit(clsDec: NormalClassDeclaration): EOBndExpr { + val nonStaticVarDecls = clsDec.body?.declarations + ?.filterIsInstance() + ?.filter { it.modifiers?.modifiers?.modifiers?.find { it == TokenCode.Static } == null && + it.initializer != null + } ?: listOf() + + val parsedInits = nonStaticVarDecls + .associate { + "d${it.hashCode()}" to listOf( + EOBndExpr( + EOObject( + listOf(), + None, + listOf( + EOBndExpr( + EOCopy( + listOf("this", it.name, "write").eoDot(), + constructInitName(it.initializer).eoDot() + ), + "@" + ) + ) + ), + "d${it.hashCode()}" + ) + ) + mapInitializer(it.initializer, constructInitName(it.initializer)) + } + + return EOBndExpr( + EOObject( + listOf("this"), + None, + listOf( + EOBndExpr( + EOCopy( + "seq", + if (parsedInits.isNotEmpty()) + parsedInits.keys.map { it.eoDot() } + else + listOf("TRUE".eoDot()) + ), + "@" + ) + ) + parsedInits.values.toList().flatten() + ), + "init" + ) +} + fun generateThis(clsDec: NormalClassDeclaration): EOBndExpr { return EOBndExpr( EOObject( @@ -33,13 +83,19 @@ fun generateThis(clsDec: NormalClassDeclaration): EOBndExpr { EOBndExpr( "super".eoDot(), "@" - ) + ), + EOBndExpr( + EOStringData(clsDec.name), + "className" + ), + generateInit(clsDec) ) + if (clsDec.body != null) clsDec.body.declarations .filter { dec: Declaration -> - dec.modifiers == null || - dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } == null + dec.modifiers?.modifiers?.modifiers?.find { it == TokenCode.Static } == null && + dec !is ConstructorDeclaration && + dec !is ClassDeclaration /* FIXME (IT'S NOT ALWAYS TRUE) */ } .map { mapClassDeclaration(it) } .flatten() diff --git a/src/main/java/util/PrimitiveTypesFinder.kt b/src/main/java/util/PrimitiveTypesFinder.kt index d5138542..8570a0f0 100644 --- a/src/main/java/util/PrimitiveTypesFinder.kt +++ b/src/main/java/util/PrimitiveTypesFinder.kt @@ -15,6 +15,7 @@ import tree.Expression.Primary.Parenthesized import tree.Initializer import tree.InitializerArray import tree.InitializerSimple +import tree.Statement.Assert import tree.Statement.BlockStatement import tree.Statement.Statement import tree.Statement.StatementExpression @@ -94,6 +95,12 @@ private fun findPrimitivesInExpression(primitives: HashSet, expr: Expres private fun findPrimitivesInStatement(primitives: HashSet, stmt: Statement) { when (stmt) { is StatementExpression -> findPrimitivesInExpression(primitives, stmt.expression) + is Assert -> { + findPrimitivesInExpression(primitives, stmt.expression) + if (stmt.expression2 != null) { + findPrimitivesInExpression(primitives, stmt.expression2) + } + } } } @@ -129,7 +136,9 @@ private fun findPrimitivesInVarDeclaration(primitives: HashSet, dec: Var ) { primitives.add(TokenCodes.CLASS__STRING.importPath) } - findPrimitivesInInitializer(primitives, dec.initializer) + if (dec.initializer != null) { + findPrimitivesInInitializer(primitives, dec.initializer) + } } private fun findPrimitivesInClass(primitives: HashSet, clsDec: NormalClassDeclaration) { diff --git a/src/main/java/util/StaticGenerator.kt b/src/main/java/util/StaticGenerator.kt index 97614623..31b4f5b1 100644 --- a/src/main/java/util/StaticGenerator.kt +++ b/src/main/java/util/StaticGenerator.kt @@ -5,19 +5,18 @@ import arrow.core.flattenOption import eotree.EOBndExpr import lexer.TokenCode import translator.mapClassDeclaration +import tree.Declaration.ClassDeclaration +import tree.Declaration.ConstructorDeclaration import tree.Declaration.Declaration import tree.Declaration.NormalClassDeclaration fun generateStatic(clsDec: NormalClassDeclaration): List { - try { - return clsDec.body.declarations - .filter { dec: Declaration -> - dec.modifiers != null && - dec.modifiers.modifiers.modifiers.find { code: TokenCode -> code == TokenCode.Static } != null - } // TODO - .map { mapClassDeclaration(it) } - .flatten() - } catch (e: NullPointerException) { - return ArrayList() - } + return clsDec.body.declarations + .filter { dec: Declaration -> + dec.modifiers?.modifiers?.modifiers?.find { it == TokenCode.Static } != null || + dec is ConstructorDeclaration || + dec is ClassDeclaration /* FIXME (IT'S NOT ALWAYS TRUE) */ + } // TODO + .map { mapClassDeclaration(it) } + .flatten() } From 22bfb0f487334a0fc541e3bc0a2a1700808e5e8b Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Sun, 22 May 2022 13:48:59 +0300 Subject: [PATCH 27/29] Added Kafka test and fixed several crashes --- .gitignore | 3 +- src/main/java/main/Main2.kt | 43 ++++++++++--------- src/main/java/parser/TreeMappings.kt | 5 ++- src/main/java/translator/Initializers.kt | 1 + src/main/java/translator/MethodInvocations.kt | 12 ++++-- .../translator/preprocessor/Preprocessor.kt | 2 +- src/main/java/util/PrimitiveTypesFinder.kt | 5 ++- test-hadoop.sh | 8 +--- test-kafka.sh | 26 +++++++++++ 9 files changed, 69 insertions(+), 36 deletions(-) create mode 100755 test-kafka.sh diff --git a/.gitignore b/.gitignore index 309b7c15..e710a9b1 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,5 @@ polystat_check .metals/ .vscode hadoop* -J2EO*.jar \ No newline at end of file +J2EO*.jar +j2eo-data diff --git a/src/main/java/main/Main2.kt b/src/main/java/main/Main2.kt index c0a800d3..f937e11d 100644 --- a/src/main/java/main/Main2.kt +++ b/src/main/java/main/Main2.kt @@ -78,30 +78,31 @@ object Main2 { } val translatedFiles: List> = filesToProcess - .reversed() .mapIndexed { i, f -> - //println("[${i+1}/${filesToProcess.size}] Parsing ${f.absolutePath}") - Scanner(f).use { _ -> - val lexer = JavaLexer(CharStreams.fromFileName(f.absolutePath)) - val parser = JavaParser(CommonTokenStream(lexer)) - val tree = parser.compilationUnit() - - val eval = Visitor() - val cu = eval.visit(tree) as CompilationUnit - - if (Entity.debug) { - cu.report(0) - logger.debug("[${i+1}/${filesToProcess.size}] Translating ${f.absolutePath}") - } else { - if (i % 100 == 0) { - val percent = (1f * i / filesToProcess.size) * 100f - print("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}\r") - } + val percent = (1f * i / filesToProcess.size) * 100f + util.logger.info("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}; file: ${f.path}") + + // Parse Java file using ANTLR parser + val lexer = JavaLexer(CharStreams.fromFileName(f.absolutePath)) + val parser = JavaParser(CommonTokenStream(lexer)) + + // Traverse the ANTLR AST + val tree = parser.compilationUnit() + val eval = Visitor() + val cu = eval.visit(tree) as CompilationUnit + + if (Entity.debug) { + cu.report(0) + logger.debug("[${i + 1}/${filesToProcess.size}] Translating ${f.absolutePath}") + } else { + if (i % 100 == 0) { + val percent = (1f * i / filesToProcess.size) * 100f + print("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}\r") } - - val translator = Translator() - Pair(f, translator.translate(cu)) } + + val translator = Translator() + Pair(f, translator.translate(cu)) } println() diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 8b8700dd..e5611446 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -156,8 +156,8 @@ fun StatementContext.toStatement(): Statement = this.expression(0).toExpression(), this.expression(1)?.toExpression() ) - is StatementBreakContext -> Break(null, identifier()?.toToken()) - is StatementContinueContext -> Continue(null, identifier()?.toToken()) + is StatementBreakContext -> Break(null, Token(TokenCode.Break)) + is StatementContinueContext -> Continue(null, Token(TokenCode.Continue)) is StatementForContext -> StatementExpression( null, SimpleReference(CompoundName("for_loop_placeholder")) @@ -249,6 +249,7 @@ fun org.antlr.v4.runtime.Token.toToken(): Token = INC -> Token(TokenCode.PlusPlus) DEC -> Token(TokenCode.MinusMinus) VAR -> Token(TokenCode.Var) + BANG -> Token(TokenCode.Negation) else -> throw Exception("unsupported token: $text ($type)") } diff --git a/src/main/java/translator/Initializers.kt b/src/main/java/translator/Initializers.kt index d23d2732..28bb76ff 100644 --- a/src/main/java/translator/Initializers.kt +++ b/src/main/java/translator/Initializers.kt @@ -4,6 +4,7 @@ import arrow.core.None import eotree.EOBndExpr import eotree.EOCopy import eotree.EOObject +import eotree.eoDot import tree.CompoundName import tree.Expression.SimpleReference import tree.Initializer diff --git a/src/main/java/translator/MethodInvocations.kt b/src/main/java/translator/MethodInvocations.kt index b7f8bbb4..3ffa9ffb 100644 --- a/src/main/java/translator/MethodInvocations.kt +++ b/src/main/java/translator/MethodInvocations.kt @@ -55,8 +55,10 @@ fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List< is SimpleReference -> (methodQualifier.compoundName.names + listOf(methodInvocation.name)).eoDot() is FieldAccess -> (getFullIdentifier(methodQualifier) + listOf(methodInvocation.name)).eoDot() null -> methodInvocation.name.eoDot() - else -> - throw IllegalArgumentException("Unsupported method qualifier!") + else -> { + util.logger.warn { "Unsupported method qualifier $methodQualifier; falling back to unsupported_qualifier" } + "unsupported_qualifier".eoDot() + } } val callee: EODot = when (val methodQualifier = methodInvocation.qualifier) { is SimpleReference -> @@ -66,8 +68,10 @@ fun mapMethodInvocation(methodInvocation: MethodInvocation, name: String): List< "this".eoDot() is FieldAccess -> getFullIdentifier(methodQualifier).eoDot() null -> "this".eoDot() - else -> - throw IllegalArgumentException("Unsupported method qualifier!") + else -> { + util.logger.warn { "Unsupported method qualifier $methodQualifier; falling back to unsupported_qualifier" } + "unsupported_qualifier".eoDot() + } } return listOf( diff --git a/src/main/java/translator/preprocessor/Preprocessor.kt b/src/main/java/translator/preprocessor/Preprocessor.kt index cff7820b..00b8599b 100644 --- a/src/main/java/translator/preprocessor/Preprocessor.kt +++ b/src/main/java/translator/preprocessor/Preprocessor.kt @@ -256,7 +256,7 @@ private fun preprocessInitializer(state: PreprocessorState, initializer: Initial when (initializer) { is InitializerSimple -> preprocessSimpleInitializer(state, initializer) is InitializerArray -> initializer.initializers - .map { preprocessInitializer(state, initializer) } + .map { preprocessInitializer(state, it) } else -> { // this is a generated else block } diff --git a/src/main/java/util/PrimitiveTypesFinder.kt b/src/main/java/util/PrimitiveTypesFinder.kt index d5138542..4a23e6b8 100644 --- a/src/main/java/util/PrimitiveTypesFinder.kt +++ b/src/main/java/util/PrimitiveTypesFinder.kt @@ -129,7 +129,10 @@ private fun findPrimitivesInVarDeclaration(primitives: HashSet, dec: Var ) { primitives.add(TokenCodes.CLASS__STRING.importPath) } - findPrimitivesInInitializer(primitives, dec.initializer) + if (dec.initializer != null) + findPrimitivesInInitializer(primitives, dec.initializer) + else + logger.warn { "findPrimitivesInVarDeclaration: dec.initializer must not be null" } } private fun findPrimitivesInClass(primitives: HashSet, clsDec: NormalClassDeclaration) { diff --git a/test-hadoop.sh b/test-hadoop.sh index 902e76f3..f3996158 100755 --- a/test-hadoop.sh +++ b/test-hadoop.sh @@ -7,12 +7,10 @@ echo "Building J2EO..." ./gradlew build -x test jar cp build/libs/J2EO-0.4.0.jar . -echo "pwd:" $(pwd) - -if [ ! -e "./j2eo-data" ]; then +if [ ! -e "./j2eo-data/hadoop-3.2.3-src" ]; then echo "Downloading Hadoop..." # get hadoop from https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz - mkdir j2eo-data + mkdir -p j2eo-data wget -O j2eo-data/hadoop.tar.gz https://dlcdn.apache.org/hadoop/common/hadoop-3.2.3/hadoop-3.2.3-src.tar.gz # unpack tar -xf j2eo-data/hadoop.tar.gz -C j2eo-data @@ -24,6 +22,4 @@ echo "Starting J2EO on Hadoop..." # clean old output rm -rf j2eo-data/hadoop-eo -# as it's not a part of the project -# we may want to output to the parent directory java -jar J2EO-0.4.0.jar -o j2eo-data/hadoop-eo j2eo-data/hadoop-3.2.3-src diff --git a/test-kafka.sh b/test-kafka.sh new file mode 100755 index 00000000..a572bfb9 --- /dev/null +++ b/test-kafka.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# Exit on error +set -e + +echo "Building J2EO..." +./gradlew build -x test jar +cp build/libs/J2EO-0.4.0.jar . + +if [ ! -e "./j2eo-data/kafka" ]; then + echo "Downloading Kafka..." + mkdir -p j2eo-data + cd j2eo-data + git clone https://github.com/apache/kafka + cd kafka + git checkout f36de0744b915335de6b636e6bd6b5f1276f34f6 + cd ../.. +else + echo "Kafka is already downloaded, skipping download..." +fi + +echo "Starting J2EO on Kafka..." +# clean old output +rm -rf j2eo-data/kafka-eo + +java -jar J2EO-0.4.0.jar -o j2eo-data/kafka-eo j2eo-data/kafka From 3a6f005f6ae780ddf0a72418a186c8cedd03d9a5 Mon Sep 17 00:00:00 2001 From: IamMaxim Date: Sun, 22 May 2022 13:55:29 +0300 Subject: [PATCH 28/29] Fixed missing import --- src/main/java/main/Main2.kt | 11 ++++++----- src/main/java/translator/Methods.kt | 7 +------ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/main/Main2.kt b/src/main/java/main/Main2.kt index f937e11d..39ae9e2c 100644 --- a/src/main/java/main/Main2.kt +++ b/src/main/java/main/Main2.kt @@ -94,12 +94,13 @@ object Main2 { if (Entity.debug) { cu.report(0) logger.debug("[${i + 1}/${filesToProcess.size}] Translating ${f.absolutePath}") - } else { - if (i % 100 == 0) { - val percent = (1f * i / filesToProcess.size) * 100f - print("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}\r") - } } +// else { +// if (i % 100 == 0) { +// val percent = (1f * i / filesToProcess.size) * 100f +// print("Progress: %.2f".format(percent) + "% / 100.0%. --- Files left: ${filesToProcess.size - i}\r") +// } +// } val translator = Translator() Pair(f, translator.translate(cu)) diff --git a/src/main/java/translator/Methods.kt b/src/main/java/translator/Methods.kt index 2cb91459..e1eefd63 100644 --- a/src/main/java/translator/Methods.kt +++ b/src/main/java/translator/Methods.kt @@ -4,17 +4,12 @@ import arrow.core.* import eotree.EOBndExpr import eotree.EOCopy import eotree.EOObject +import eotree.eoDot import lexer.TokenCode import tree.Declaration.ConstructorDeclaration import tree.Declaration.MethodDeclaration import tree.Declaration.ParameterDeclaration -// fun MethodDeclaration.getLocalVariables(): List = -// // TODO: add support for nested block variables as well -// methodBody.block.blockStatements -// .filter { it.declaration != null } -// .map { } - fun mapMethodDeclaration(dec: MethodDeclaration): EOBndExpr { val isStatic = dec.modifiers != null && dec.modifiers.modifiers.modifiers.find { it == TokenCode.Static } != null From e10c8eda48f0c6201e0f02562e01b350a99457d9 Mon Sep 17 00:00:00 2001 From: someilay Date: Mon, 23 May 2022 21:26:31 +0300 Subject: [PATCH 29/29] Hot fix --- src/main/java/parser/TreeMappings.kt | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/parser/TreeMappings.kt b/src/main/java/parser/TreeMappings.kt index 53f37b6f..9f0a718a 100644 --- a/src/main/java/parser/TreeMappings.kt +++ b/src/main/java/parser/TreeMappings.kt @@ -317,25 +317,29 @@ fun org.antlr.v4.runtime.Token.toToken(): Token = DEC -> Token(TokenCode.MinusMinus) VAR -> Token(TokenCode.Var) BANG -> Token(TokenCode.Negation) + TILDE -> Token(TokenCode.Tilde) else -> throw Exception("unsupported token: $text ($type)") } fun CompoundName.toExpression(): Expression = SimpleReference(this) fun ExpressionContext.toBinaryExpression(): Binary? { - val expr0 = expression(0)?.toExpression() - val expr1 = expression(1)?.toExpression() + val weakExpr0 = expression(0) + val weakExpr1 = expression(1) val operand = terminal(0)?.symbol - return if (expr0 != null && expr1 != null && operand != null) + return if (weakExpr0 != null && weakExpr1 != null && operand != null) { + val expr0 = weakExpr0.toExpression() + val expr1 = weakExpr1.toExpression() Binary(expr0, expr1, operand.toToken()) - else + } else null } fun ExpressionContext.toUnaryPrefixPostfix(): Expression? { - val expr = expression(0)?.toExpression() + val weakExpr = expression(0) val operand = terminal(0)?.symbol - return if (expr != null && operand != null) { + return if (weakExpr != null && operand != null && childCount == 2) { + val expr = weakExpr.toExpression() if (prefix != null) { UnaryPrefix(operand.toToken(), expr) } else if (postfix != null) {