diff --git a/.gitignore b/.gitignore index d35b73a..3f9d58b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,4 @@ .gradle build -bin \ No newline at end of file +bin diff --git a/build.gradle b/build.gradle index 054f743..3d78ca6 100644 --- a/build.gradle +++ b/build.gradle @@ -17,16 +17,21 @@ sourceSets { srcDirs = ['src/test/java'] } } + playground { + java { + srcDirs = ['src/playground/java'] + } + } } dependencies { - implementation platform('org.junit:junit-bom:5.10.3') - implementation 'org.junit.jupiter:junit-jupiter' - testImplementation platform('org.junit:junit-bom:5.10.3') testImplementation 'org.junit.jupiter:junit-jupiter' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + playgroundImplementation sourceSets.main.output + // playgroundImplementation configurations.implementation + // playgroundRuntimeOnly configurations.runtimeClasspath } import org.gradle.api.tasks.testing.logging.TestExceptionFormat @@ -49,17 +54,25 @@ tasks.named('test') { events = [TestLogEvent.STARTED, TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.STANDARD_ERROR, TestLogEvent.STANDARD_OUT] exceptionFormat = TestExceptionFormat.FULL } - + info.events = debug.events info.exceptionFormat = debug.exceptionFormat afterSuite { desc, result -> - if (!desc.parent) { - def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)" - def startItem = '| ', endItem = ' |' - def repeatLength = startItem.length() + output.length() + endItem.length() - println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength)) - } + if (desc.parent) return + + def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)" + def startItem = '| ', endItem = ' |' + def repeatLength = startItem.length() + output.length() + endItem.length() + + println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength)) } } } + +tasks.register('playground', JavaExec) { + group = 'application' + description = 'Runs the playground main method' + classpath = sourceSets.playground.runtimeClasspath + mainClass = 'Test' +} \ No newline at end of file diff --git a/docs/diagrams/CustomCompilers.drawio.svg b/docs/diagrams/CustomCompilers.drawio.svg new file mode 100644 index 0000000..0cbb1f4 --- /dev/null +++ b/docs/diagrams/CustomCompilers.drawio.svg @@ -0,0 +1,1283 @@ + + + + + + + + + + + + + + + + + + + + + StorableCustomCompilerBuilder + + + + + + + + + StorableCustomCompilerBuilder + + + + + + + + + + + + + + + + + + + Loads + + + + + + Loads + + + + + + + + + + + + + + Load + + + + + + Load + + + + + + + + + + + + + + + + + + + + + CompilerStorage + + + + + + + + + CompilerStorage + + + + + + + + + + + + + + + + + + + <A> + + + CompilerBuilderTemplate + + + + + + + + <A> CompilerBuilderTemplate + + + + + + + + + + + + + + + + + + + Store + + + + + + Store + + + + + + + + + + + + + + + + + + + + User creates + + + + + + User creates + + + + + + + + + + + + + + + + + + + + + StorableCustomCompiler + + + + + + + + + StorableCustomCompiler + + + + + + + + + + + + + + + + + + + + <I> LexicalAnalyserFactory + + + + + + + + + <I> LexicalAnalyserFactory + + + + + + + + + + + + + + + + + + + + <I> SyntaxAnalyserFactory + + + + + + + + + <I> SyntaxAnalyserFactory + + + + + + + + + + + + + + + + + + + + <I> CodeGeneratorFactory + + + + + + + + + <I> CodeGeneratorFactory + + + + + + + + + + + + + + + + + + + + CustomCompiler + + + + + + + + + CustomCompiler + + + + + + + + + + + + + + + + + + <I> Compiler + + + + + + + <I> Compiler + + + + + + + + + + + + + + + + + + + + + + + + <I> Storable + + + + + + + <I> Storable + + + + + + + + + + + + + + + + + + + References + + + + + + References + + + + + + + + + + + + + + + + + + + <I> LoadableBy<T> + + T = StorableCustomCompilerFactory> + + + + + + + + <I> LoadableBy<T> + + + T = StorableCustomCompilerFactory> + + + + + + + + + + + + + + + + + + + + Uses + + + + + + Uses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + StorableCustomCompilerFactory + + + + + + + + + StorableCustomCompilerFactory + + + + + + + + + + + + + + + + + + + + + + + + <I> Loader<T> + + T = StorableCustomCompiler + + + + + + + + <I> Loader<T> + + + T = StorableCustomCompiler + + + + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + + + + + + + + ReflectiveClassConstructor + + + + + + + + + ReflectiveClassConstructor + + + + + + + + + + + + + + + + + + <I> Factory<T> + + + + + + + <I> Factory<T> + + + + + + + + + + + + + + + + + + Storage + + + + + + + Storage + + + + + + + + + + + + + + + + + + Component Construcion + + + + + + Component Construcion + + + + + + + + + + + + + + + + + + Factories + + + + + + Factories + + + + + + + + + + + + + + + + + + Builders + + + + + + Builders + + + + + + + + + + + + + + + + + + + + + + + + + + CustomCompilerFactory + + + + + + + + + CustomCompilerFactory + + + + + + + + + + + + + + + + + + Custom Compiler + + + + + + Custom Compiler + + + + + + + + + + + + + + + + + + <I> Loader<T> + + + + + + + <I> Loader<T> + + + + + + + + + + + + + + + + + + Dynamic Loading + + + + + + Dynamic Loading + + + + + + + + + + + + + + + + + + + + + + + + + Builds + + + + + + Builds + + + + + + + + + + + + + + + + + + + + + + + + + + Uses + + + + + + Uses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Uses + + + + + + Uses + + + + + + + + + + + + + + + + + + + Storable + + + + + + Storable + + + + + + + + + + + + + + + + + + Builders + + + + + + Builders + + + + + + + + + + + + + + + + + + + + ComponentCastException + + + + + + + + + ComponentCastException + + + + + + + + + + + + + + + + + + + + IncorrectLoadValueFormat + + + + + + + + + IncorrectLoadValueFormat + + + + + + + + + + + + + + + + + + + + IncorrectlyFormattedException + + + + + + + + + IncorrectlyFormattedException + + + + + + + + + + + + + + + + + + + + MissingEmptyConstructorException + + + + + + + + + MissingEmptyConstructorException + + + + + + + + + + + + + + + + + + + + MissingKeyException + + + + + + + + + MissingKeyException + + + + + + + + + + + + + + + + + + + + NonExistentComponentException + + + + + + + + + NonExistentComponentException + + + + + + + + + + + + + + + + + + + + NonStorableComponentException + + + + + + + + + NonStorableComponentException + + + + + + + + + + + + + + + + + + + + ReflectiveLoadFailure + + + + + + + + + ReflectiveLoadFailure + + + + + + + + + + + + + + + + + + Exceptions + + + + + + Exceptions + + + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + Text is not SVG - cannot display + + + + \ No newline at end of file diff --git a/docs/diagrams/Storage.drawio.svg b/docs/diagrams/Storage.drawio.svg new file mode 100644 index 0000000..174ce39 --- /dev/null +++ b/docs/diagrams/Storage.drawio.svg @@ -0,0 +1,728 @@ + + + + + + + + + + + + + + Storable <I> + + + + + + Storable <... + + + + + + + + + + + + + + + + + Storage Values + + + + + + Storage Values + + + + + + + + + + + + + + + StorageValue<T> + + <A> + + + + + + StorageValue<T>... + + + + + + + + + + + + + + + StringStorageValue + + + + + + StringStorageValue + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + + + + + + + + Value Formatters + + + + + + Value Formatters + + + + + + + + + + + + + + + ValueFormatter<T> + + <I> + + + + + + ValueFormatter<T>... + + + + + + + + + + + + + + + ValueToStringFormatter + + + + + + ValueToStringFormatter + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + + + Loadable <I> + + + + + + Loadable <... + + + + + + + + + + + + + + + + Produces a set of + + + + + + Produces a set of + + + + + + + + + + + + + + + Component + + + + + + Component + + + + + + + + + + + + + + + + + Storage Value Adapters + + + + + + Storage Value Adapters + + + + + + + + + + + + + + + StorageValueAdapter <I> + + + + + + StorageValueAdapter <... + + + + + + + + + + + + + + + StringValueToString + + + + + + StringValueToString + + + + + + + + + + + + + + + UnsupportedValueException + + + + + + UnsupportedValueException + + + + + + + + + + + + + + + + + + + + Passed into + + + + + + Passed into + + + + + + + + + + + + + + + RuntimeException + + + + + + RuntimeException + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + + + + + + + + Throws + + + + + + Throws + + + + + + + + + + + + + + + + String Data Stream + + + + + + String Data... + + + + + + + + + + + + + + + + Produces + + + + + + Produces + + + + + + + + + + + + + + + + + + + Storage Representation + + + + + + Storage Represen... + + + + + + + + + + + + + + + + + Stream Editors + + + + + + Stream Editors + + + + + + + + + + + + + + + StreamWriter<T> + + <I> + + + + + + StreamWriter<T>... + + + + + + + + + + + + + + + StringStreamWriter + + + + + + StringStreamWriter + + + + + + + + + + + + + + + StreamReader<T> + + <I> + + + + + + StreamReader<T>... + + + + + + + + + + + + + + + StreamEditor<T> + + <A> + + + + + + StreamEditor<T>... + + + + + + + + + + + + + + + + Extends + + + + + + Extends + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Text + + + + + + Text + + + + + + + + + + + + + + + + Data File + + + + + + Data File + + + + + + + + + + Text is not SVG - cannot display + + + + \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index d64cd49..d997cfc 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9355b41..dbc3ce4 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 1aa94a4..0262dcb 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -112,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -170,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -203,15 +203,14 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..c4bdd3a 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,22 +59,21 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell diff --git a/src/main/java/component_construction/Compiler.java b/src/main/java/component_construction/Compiler.java index 7ff7b57..92486ef 100644 --- a/src/main/java/component_construction/Compiler.java +++ b/src/main/java/component_construction/Compiler.java @@ -1,30 +1,14 @@ package component_construction; - -import code_generation.CodeGenerator; -import grammar_objects.Token; -import lexical_analysis.LexicalAnalyser; -import syntax_analysis.SyntaxAnalyser; import syntax_analysis.parsing.ParseFailedException; -import syntax_analysis.parsing.ParseState; -public class Compiler { - protected LexicalAnalyser lexicalAnalyser; - protected SyntaxAnalyser syntaxAnalyser; - protected CodeGenerator codeGenerator; - - public Compiler( - LexicalAnalyser lexicalAnalyser, - SyntaxAnalyser syntaxAnalyser, - CodeGenerator codeGenerator - ) { - this.lexicalAnalyser = lexicalAnalyser; - this.syntaxAnalyser = syntaxAnalyser; - this.codeGenerator = codeGenerator; - } +public interface Compiler { + + /** + * Compiles an input sentence + * @param input The sentence to be compiled + * @return The output of compilation + * @throws ParseFailedException An error occurred when parsing the sentence + */ + public String compile(String input) throws ParseFailedException; - public String compile(String input) throws ParseFailedException { - Token[] tokens = lexicalAnalyser.analyse(input); - ParseState parseRoot = syntaxAnalyser.analyse(tokens); - return codeGenerator.generate(parseRoot); - } } diff --git a/src/main/java/component_construction/builders/CompilerBuilder.java b/src/main/java/component_construction/builders/CompilerBuilder.java deleted file mode 100644 index 2a11c63..0000000 --- a/src/main/java/component_construction/builders/CompilerBuilder.java +++ /dev/null @@ -1,189 +0,0 @@ -package component_construction.builders; - -import java.util.*; - -import grammar_objects.*; -import lexical_analysis.*; -import syntax_analysis.SyntaxAnalyser; -import code_generation.CodeGenerator; -import component_construction.Compiler; -import component_construction.ParameterError; -import component_construction.bundles.GrammarBundle; -import component_construction.factories.code_generation.CodeGeneratorFactory; -import component_construction.factories.lexical_analysis.LexicalAnalyserFactory; -import component_construction.factories.syntax_analysis.SyntaxAnalyserFactory; - -public class CompilerBuilder { - protected LexicalAnalyserFactory lexicalAnalyserFactory; - protected SyntaxAnalyserFactory syntaxAnalyserFactory; - protected CodeGeneratorFactory codeGeneratorFactory; - - protected Grammar grammar; - protected RuleConvertor ruleConvertor; - - protected String[] whitespaceDelimiters; - protected String[] stronglyReservedWords; - protected String[] weaklyReservedWords; - protected DynamicTokenRegex[] dynamicTokenRegex; - - /** - * A shortcut setter method for all components necessary for building a compiler - * @param lexicalAnalyserFactory - * @param syntaxAnalyserFactory - * @param codeGeneratorFactory - * @param grammarBundle - */ - public CompilerBuilder setComponents( - LexicalAnalyserFactory lexicalAnalyserFactory, - SyntaxAnalyserFactory syntaxAnalyserFactory, - CodeGeneratorFactory codeGeneratorFactory, - GrammarBundle grammarBundle - ) { - return setComponents( - lexicalAnalyserFactory, - syntaxAnalyserFactory, - codeGeneratorFactory, - grammarBundle.getGrammar(), - grammarBundle.getRuleConvertor(), - grammarBundle.getWhitespaceDelimiters(), - grammarBundle.getStronglyReservedWords(), - grammarBundle.getWeaklyReservedWords(), - grammarBundle.getDynamicTokenRegex() - ); - } - - /** - * A shortcut setter method for all components necessary for building a compiler - * @param lexicalAnalyserFactory - * @param syntaxAnalyserFactory - * @param codeGeneratorFactory - * @param grammar - * @param ruleConvertor - * @param whitespaceDelimiters May be null - * @param stronglyReservedWords May be null - * @param weaklyReservedWords May be null - * @param dynamicTokenRegex May be null - */ - public CompilerBuilder setComponents( - LexicalAnalyserFactory lexicalAnalyserFactory, - SyntaxAnalyserFactory syntaxAnalyserFactory, - CodeGeneratorFactory codeGeneratorFactory, - Grammar grammar, - RuleConvertor ruleConvertor, - String[] whitespaceDelimiters, - String[] stronglyReservedWords, - String[] weaklyReservedWords, - DynamicTokenRegex[] dynamicTokenRegex - ) { - setLexicalAnalyser(lexicalAnalyserFactory); - setSyntaxAnalyser(syntaxAnalyserFactory); - setCodeGenerator(codeGeneratorFactory); - setGrammar(grammar); - setRuleConvertor(ruleConvertor); - setWhitespaceDelimiters(whitespaceDelimiters); - setStronglyReservedWords(stronglyReservedWords); - setWeaklyReservedWords(weaklyReservedWords); - setDynamicTokenRegex(dynamicTokenRegex); - - return this; - } - - - public CompilerBuilder setLexicalAnalyser(LexicalAnalyserFactory factory) { - this.lexicalAnalyserFactory = factory; - return this; - } - - public CompilerBuilder setSyntaxAnalyser(SyntaxAnalyserFactory factory) { - this.syntaxAnalyserFactory = factory; - return this; - } - - public CompilerBuilder setCodeGenerator(CodeGeneratorFactory factory) { - this.codeGeneratorFactory = factory; - return this; - } - - - public CompilerBuilder setGrammar(Grammar grammar) { - this.grammar = grammar; - return this; - } - - public CompilerBuilder setRuleConvertor(RuleConvertor ruleConvertor) { - this.ruleConvertor = ruleConvertor; - return this; - } - - - public CompilerBuilder setWhitespaceDelimiters(String[] whitespaceDelimiters) { - this.whitespaceDelimiters = whitespaceDelimiters; - return this; - } - - public CompilerBuilder setStronglyReservedWords(String[] stronglyReservedWords) { - this.stronglyReservedWords = stronglyReservedWords; - return this; - } - - public CompilerBuilder setWeaklyReservedWords(String[] weaklyReservedWords) { - this.weaklyReservedWords = weaklyReservedWords; - return this; - } - - public CompilerBuilder setDynamicTokenRegex(DynamicTokenRegex[] dynamicTokenRegex) { - this.dynamicTokenRegex = dynamicTokenRegex; - return this; - } - - - public Compiler createCompiler() { - checkForCompleteBuild(); - - if(whitespaceDelimiters == null) whitespaceDelimiters = new String[]{}; - if(stronglyReservedWords == null) stronglyReservedWords = new String[]{}; - if(weaklyReservedWords == null) weaklyReservedWords = new String[]{}; - if(dynamicTokenRegex == null) dynamicTokenRegex = new DynamicTokenRegex[]{}; - - GrammarParts parts = grammar.getParts(); - - LexicalAnalyser lexicalAnalyser = lexicalAnalyserFactory.produceAnalyser( - whitespaceDelimiters, - stronglyReservedWords, - weaklyReservedWords, - dynamicTokenRegex - ); - SyntaxAnalyser syntaxAnalyser = syntaxAnalyserFactory.produceAnalyser(parts); - CodeGenerator codeGenerator = codeGeneratorFactory.produceGenerator(ruleConvertor); - - return new Compiler( - lexicalAnalyser, - syntaxAnalyser, - codeGenerator - ); - } - - private void checkForCompleteBuild() { - List msgParts = new ArrayList<>(); - - if(lexicalAnalyserFactory == null) msgParts.add("lexical analyser factory"); - if(syntaxAnalyserFactory == null) msgParts.add("syntax analyser factory"); - if(codeGeneratorFactory == null) msgParts.add("code generator factory"); - if(grammar == null) msgParts.add("grammar"); - if(ruleConvertor == null) msgParts.add("rule convertor"); - //Note: Allowing null lexical components - - if(msgParts.size() == 0) return; //No error - if(msgParts.size() == 1) throw new ParameterError(msgParts.get(0) + " not provided"); - - String msg = msgParts.get(0); - - for(int i = 1; i < msgParts.size() - 1; i++) { - msg += ", " + msgParts.get(i); - } - - msg += " and " + msgParts.get(msgParts.size() - 1) + " not provided"; - - throw new ParameterError(msg); - } -} diff --git a/src/main/java/component_construction/builders/CompilerBuilderTemplate.java b/src/main/java/component_construction/builders/CompilerBuilderTemplate.java new file mode 100644 index 0000000..8872179 --- /dev/null +++ b/src/main/java/component_construction/builders/CompilerBuilderTemplate.java @@ -0,0 +1,226 @@ +package component_construction.builders; + +import java.util.*; + +import grammar_objects.*; +import lexical_analysis.*; +import component_construction.ParameterError; +import component_construction.bundles.GrammarBundle; +import component_construction.custom_components.*; +import component_construction.factories.code_generation.CodeGeneratorFactory; +import component_construction.factories.lexical_analysis.LexicalAnalyserFactory; +import component_construction.factories.syntax_analysis.SyntaxAnalyserFactory; + +/** + * An template for builders of CustomCompilers + * @param The type of the current implementing subclass of this template + * @param The type of CustomCompiler that will be built by the implemented builder + */ +public abstract class CompilerBuilderTemplate , C extends CustomCompiler> { + protected LexicalAnalyserFactory lexicalAnalyserFactory; + protected SyntaxAnalyserFactory syntaxAnalyserFactory; + protected CodeGeneratorFactory codeGeneratorFactory; + + protected Grammar grammar; + protected RuleConvertor ruleConvertor; + + protected String[] whitespaceDelimiters; + protected String[] stronglyReservedWords; + protected String[] weaklyReservedWords; + protected DynamicTokenRegex[] dynamicTokenRegex; + + /** + * A shortcut setter method for all components necessary for building a compiler + * @param lexicalAnalyserFactory A factory which produces lexical analysers + * @param syntaxAnalyserFactory A factory which produces syntax analysers + * @param codeGeneratorFactory A factory which produces code generators + * @param grammarBundle A {@code GrammarBundle} for the grammar to be compiled + * @return This object for method chaining + */ + public B setComponents( + LexicalAnalyserFactory lexicalAnalyserFactory, + SyntaxAnalyserFactory syntaxAnalyserFactory, + CodeGeneratorFactory codeGeneratorFactory, + GrammarBundle grammarBundle + ) { + return setComponents( + lexicalAnalyserFactory, + syntaxAnalyserFactory, + codeGeneratorFactory, + grammarBundle.getGrammar(), + grammarBundle.getRuleConvertor(), + grammarBundle.getWhitespaceDelimiters(), + grammarBundle.getStronglyReservedWords(), + grammarBundle.getWeaklyReservedWords(), + grammarBundle.getDynamicTokenRegex() + ); + } + + /** + * A shortcut setter method for all components necessary for building a compiler + * @param lexicalAnalyserFactory A factory which produces lexical analysers + * @param syntaxAnalyserFactory A factory which produces syntax analysers + * @param codeGeneratorFactory A factory which produces code generators + * @param grammar The {@code grammar} to be used for compilation + * @param ruleConvertor The {@code RuleConvertor} to produce output code from compiled input sentences + * @param whitespaceDelimiters An array of strings to be conidered as whitespace in compiled sentences. May be null + * @param stronglyReservedWords An array of strings which may only be used by reserved words within the provided grammar. May be null + * @param weaklyReservedWords An array of strings to be used by reserved words within the provided grammar, they may appear as part of other tokens. May be null + * @param dynamicTokenRegex An array of {@code DynamicTokenRegex} for grammar tokens which may take different forms according to provided regex. May be null + * @return This object for method chaining + */ + public B setComponents( + LexicalAnalyserFactory lexicalAnalyserFactory, + SyntaxAnalyserFactory syntaxAnalyserFactory, + CodeGeneratorFactory codeGeneratorFactory, + Grammar grammar, + RuleConvertor ruleConvertor, + String[] whitespaceDelimiters, + String[] stronglyReservedWords, + String[] weaklyReservedWords, + DynamicTokenRegex[] dynamicTokenRegex + ) { + setLexicalAnalyser(lexicalAnalyserFactory); + setSyntaxAnalyser(syntaxAnalyserFactory); + setCodeGenerator(codeGeneratorFactory); + setGrammar(grammar); + setRuleConvertor(ruleConvertor); + setWhitespaceDelimiters(whitespaceDelimiters); + setStronglyReservedWords(stronglyReservedWords); + setWeaklyReservedWords(weaklyReservedWords); + setDynamicTokenRegex(dynamicTokenRegex); + + return getThis(); + } + + + /** + * Sets the lexical analyser for the produced compiler + * @param factory A factory which produces lexical analysers + * @return This object for method chaining + */ + public B setLexicalAnalyser(LexicalAnalyserFactory factory) { + this.lexicalAnalyserFactory = factory; + return getThis(); + } + + /** + * Sets the syntax analyser for the produced compiler + * @param factory A factory which produces syntax analysers + * @return This object for method chaining + */ + public B setSyntaxAnalyser(SyntaxAnalyserFactory factory) { + this.syntaxAnalyserFactory = factory; + return getThis(); + } + + /** + * Sets the code generator for the produced compiler + * @param factory A factory which produces code generators + * @return This object for method chaining + */ + public B setCodeGenerator(CodeGeneratorFactory factory) { + this.codeGeneratorFactory = factory; + return getThis(); + } + + + /** + * Sets the grammar for the produced compiler + * @param grammar The {@code grammar} to be used for compilation + * @return This object for method chaining + */ + public B setGrammar(Grammar grammar) { + this.grammar = grammar; + return getThis(); + } + + /** + * Sets the rule convertor for the produced compiler + * @param ruleConvertor The {@code RuleConvertor} to produce output code from compiled input sentences + * @return This object for method chaining + */ + public B setRuleConvertor(RuleConvertor ruleConvertor) { + this.ruleConvertor = ruleConvertor; + return getThis(); + } + + + /** + * Sets the designated whitespace delimiters for compilation + * @param whitespaceDelimiters An array of strings to be conidered as whitespace in compiled sentences + * @return This object for method chaining + */ + public B setWhitespaceDelimiters(String[] whitespaceDelimiters) { + this.whitespaceDelimiters = whitespaceDelimiters; + return getThis(); + } + + /** + * Sets designated reserved words for compilation. These may not be used within other tokens + * @param stronglyReservedWords An array of strings which may only be used by reserved words within the provided grammar + * @return This object for method chaining + */ + public B setStronglyReservedWords(String[] stronglyReservedWords) { + this.stronglyReservedWords = stronglyReservedWords; + return getThis(); + } + + /** + * Sets reserved words for compilation that may be used as part of other tokens + * @param weaklyReservedWords An array of strings to be used by reserved words within the provided grammar, they may appear within other tokens + * @return This object for method chaining + */ + public B setWeaklyReservedWords(String[] weaklyReservedWords) { + this.weaklyReservedWords = weaklyReservedWords; + return getThis(); + } + + /** + * Sets the dynaic tokens for comiplation + * @param dynamicTokenRegex An array of {@code DynamicTokenRegex} for grammar tokens which may take different forms according to provided regex + * @return This object for method chaining + */ + public B setDynamicTokenRegex(DynamicTokenRegex[] dynamicTokenRegex) { + this.dynamicTokenRegex = dynamicTokenRegex; + return getThis(); + } + + + /** + * Creates a new compiler according to the components provided to this builder + * @return The produced compiler + */ + public abstract C createCompiler(); + + + /** + * A simple helper method to be filled with "{@code return this;}" by subclasses of this builder + * @return The current builder object "this" + */ + protected abstract B getThis(); + + protected void checkForCompleteBuild() { + List msgParts = new ArrayList<>(); + + if(lexicalAnalyserFactory == null) msgParts.add("lexical analyser factory"); + if(syntaxAnalyserFactory == null) msgParts.add("syntax analyser factory"); + if(codeGeneratorFactory == null) msgParts.add("code generator factory"); + if(grammar == null) msgParts.add("grammar"); + if(ruleConvertor == null) msgParts.add("rule convertor"); + // Note: Allowing null lexical components + + if(msgParts.size() == 0) return; // No error + if(msgParts.size() == 1) throw new ParameterError(msgParts.get(0) + " not provided"); + + String msg = msgParts.get(0); + + for(int i = 1; i < msgParts.size() - 1; i++) { + msg += ", " + msgParts.get(i); + } + + msg += " and " + msgParts.get(msgParts.size() - 1) + " not provided"; + + throw new ParameterError(msg); + } +} diff --git a/src/main/java/component_construction/builders/CustomCompilerBuilder.java b/src/main/java/component_construction/builders/CustomCompilerBuilder.java new file mode 100644 index 0000000..9ced170 --- /dev/null +++ b/src/main/java/component_construction/builders/CustomCompilerBuilder.java @@ -0,0 +1,29 @@ +package component_construction.builders; + +import component_construction.custom_components.*; + +public class CustomCompilerBuilder extends CompilerBuilderTemplate { + + @Override + protected CustomCompilerBuilder getThis() { + return this; + } + + @Override + public CustomCompiler createCompiler() { + checkForCompleteBuild(); + + return new CustomCompilerFactory().produce( + lexicalAnalyserFactory, + syntaxAnalyserFactory, + codeGeneratorFactory, + grammar, + ruleConvertor, + whitespaceDelimiters, + stronglyReservedWords, + weaklyReservedWords, + dynamicTokenRegex + ); + } + +} diff --git a/src/main/java/component_construction/custom_components/CustomCompiler.java b/src/main/java/component_construction/custom_components/CustomCompiler.java new file mode 100644 index 0000000..5a8626f --- /dev/null +++ b/src/main/java/component_construction/custom_components/CustomCompiler.java @@ -0,0 +1,53 @@ +package component_construction.custom_components; + +import code_generation.CodeGenerator; +import component_construction.Compiler; +import grammar_objects.Token; +import lexical_analysis.LexicalAnalyser; +import syntax_analysis.SyntaxAnalyser; +import syntax_analysis.parsing.*; + +/** + * A compiler that can be built with user-definable inner components + */ +public class CustomCompiler implements Compiler { + protected LexicalAnalyser lexicalAnalyser; + protected SyntaxAnalyser syntaxAnalyser; + protected CodeGenerator codeGenerator; + + public CustomCompiler( + LexicalAnalyser lexicalAnalyser, + SyntaxAnalyser syntaxAnalyser, + CodeGenerator codeGenerator + ) { + this.lexicalAnalyser = lexicalAnalyser; + this.syntaxAnalyser = syntaxAnalyser; + this.codeGenerator = codeGenerator; + } + + public String compile(String input) throws ParseFailedException { + Token[] tokens = lexicalAnalyser.analyse(input); + ParseState parseRoot = syntaxAnalyser.analyse(tokens); + return codeGenerator.generate(parseRoot); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CustomCompiler)) return false; + + CustomCompiler other = (CustomCompiler)obj; + if (!this.lexicalAnalyser.equals(other.lexicalAnalyser)) return false; + if (!this.syntaxAnalyser.equals(other.syntaxAnalyser)) return false; + if (!this.codeGenerator.equals(other.codeGenerator)) return false; + + return true; + } + + @Override + public int hashCode() { + return 31 + * lexicalAnalyser.hashCode() + * syntaxAnalyser.hashCode() + * codeGenerator.hashCode(); + } +} \ No newline at end of file diff --git a/src/main/java/component_construction/custom_components/CustomCompilerFactory.java b/src/main/java/component_construction/custom_components/CustomCompilerFactory.java new file mode 100644 index 0000000..04d139c --- /dev/null +++ b/src/main/java/component_construction/custom_components/CustomCompilerFactory.java @@ -0,0 +1,62 @@ +package component_construction.custom_components; + +import code_generation.CodeGenerator; +import component_construction.factories.code_generation.CodeGeneratorFactory; +import component_construction.factories.lexical_analysis.LexicalAnalyserFactory; +import component_construction.factories.syntax_analysis.SyntaxAnalyserFactory; +import grammar_objects.Grammar; +import grammar_objects.RuleConvertor; +import lexical_analysis.*; +import syntax_analysis.SyntaxAnalyser; + +/** + * A factory for {@code CustomCompilers} + */ +public class CustomCompilerFactory { + + /** + * Builds and produces a {@code CustomCompiler} with user-specified components + * @param lexicalAnalyserFactory A factory for producing {@code LexicalAnalysers} for use within produced {@code CustomCompilers} + * @param syntaxAnalyserFactory A factory for producing {@code SyntaxAnalysers} for use within produced {@code CustomCompilers} + * @param codeGeneratorFactory A factory for producing {@code CodeGenerators} for use within produced {@code CustomCompilers} + * @param grammar The grammar to be used by produced {@code CustomCompilers} + * @param ruleConvertor The convertor to sanction grammar rules within produced {@code CustomCompilers} + * @param whitespaceDelimiters An array of designated whitespace delimiter strings for compilation + * @param stronglyReservedWords An array of designated reserved words for compilation. These words may not be used within other tokens + * @param weaklyReservedWords An array of reserved words that may be used as part of other tokens + * @param dynamicTokenRegex An array of {@code DynamicTokenRegex} for tokens whix may take many forms according to the provided regex + * @return A produced {@code CustomCompiler} + */ + public CustomCompiler produce( + LexicalAnalyserFactory lexicalAnalyserFactory, + SyntaxAnalyserFactory syntaxAnalyserFactory, + CodeGeneratorFactory codeGeneratorFactory, + Grammar grammar, + RuleConvertor ruleConvertor, + String[] whitespaceDelimiters, + String[] stronglyReservedWords, + String[] weaklyReservedWords, + DynamicTokenRegex[] dynamicTokenRegex + ) { + if(whitespaceDelimiters == null) whitespaceDelimiters = new String[]{}; + if(stronglyReservedWords == null) stronglyReservedWords = new String[]{}; + if(weaklyReservedWords == null) weaklyReservedWords = new String[]{}; + if(dynamicTokenRegex == null) dynamicTokenRegex = new DynamicTokenRegex[]{}; + + LexicalAnalyser lexicalAnalyser = lexicalAnalyserFactory.produceAnalyser( + whitespaceDelimiters, + stronglyReservedWords, + weaklyReservedWords, + dynamicTokenRegex + ); + SyntaxAnalyser syntaxAnalyser = syntaxAnalyserFactory.produceAnalyser(grammar.getParts()); + CodeGenerator codeGenerator = codeGeneratorFactory.produceGenerator(ruleConvertor); + + return new CustomCompiler( + lexicalAnalyser, + syntaxAnalyser, + codeGenerator + ); + } + +} diff --git a/src/main/java/component_construction/factories/syntax_analysis/CLR1ParserFactory.java b/src/main/java/component_construction/factories/syntax_analysis/CLR1ParserFactory.java index ca65ce4..ec9a800 100644 --- a/src/main/java/component_construction/factories/syntax_analysis/CLR1ParserFactory.java +++ b/src/main/java/component_construction/factories/syntax_analysis/CLR1ParserFactory.java @@ -2,6 +2,7 @@ import grammar_objects.GrammarParts; import syntax_analysis.*; +import syntax_analysis.parsing.parsers.CLR1Parser; public class CLR1ParserFactory implements SyntaxAnalyserFactory { diff --git a/src/main/java/component_construction/storable/CompilerStorage.java b/src/main/java/component_construction/storable/CompilerStorage.java new file mode 100644 index 0000000..91f5465 --- /dev/null +++ b/src/main/java/component_construction/storable/CompilerStorage.java @@ -0,0 +1,279 @@ +package component_construction.storable; + +import java.io.*; +import java.nio.file.Path; + +import component_construction.storable.factories.StorableCustomCompilerFactory; +import storage.Storage; +import storage.exceptions.*; +import storage.external_interfaces.Loadable; +import storage.file_editors.*; +import storage.storage_value_adapters.UnsupportedValueException; +import storage.storage_values.StorageValue; +import storage.value_formatters.ValueFormatter; + +public class CompilerStorage { + protected Storage storage = new Storage(); + protected StorableCustomCompilerFactory storableCustomCompilerFactory = new StorableCustomCompilerFactory(); + + //#region Getters + + /** + * Gets the currently tagetted filepath being used for storage + * @return The targeted filepath + */ + public Path getTargetFilepath() { + return storage.getTargetFilepath(); + } + + //#endregion + + //#region Configuration + + /** + * Sets the target filepath the be use for storage + * @param filepath The filepath to target + * @return This object for method chaining + */ + public CompilerStorage setTargetPath(Path filepath) { + storage.setTargetPath(filepath); + return this; + } + + /** + * Sets the target filepath the be use for storage + * @param filepath The absolute filepath to be targeted + * @return This object for method chaining + */ + public CompilerStorage setAbsoluteTargetPath(String filepath) { + storage.setAbsoluteTargetPath(filepath); + return this; + } + + /** + * Sets the target filepath the be use for storage + * @param filepath The relative filepath to be targeted + * @return This object for method chaining + */ + public CompilerStorage setRelativeTargetPath(String filepath) { + storage.setRelativeTargetPath(filepath); + return this; + } + + /** + * Sets the formatter to be used for converting StorageValues into storage representations + * @param The target format to convert values to/from + * @param formatter The formatter to be used + * @return This object for method chaining + */ + public CompilerStorage setFormatter(ValueFormatter formatter) { + storage.setFormatter(formatter); + return this; + } + + /** + * Sets the stream writer to be used for storing storage values + * @param The data format expected to be writen + * @param streamWriter The stream writer to be selected + * @return This object for method chaining + */ + public CompilerStorage setStreamWriter(StreamWriter streamWriter) { + storage.setStreamWriter(streamWriter); + return this; + } + + /** + * Sets the stream reader to be used for reading values from storage + * @param The data format expected to be output when read + * @param streamReader The stream reader to be selected + * @return This object for method chaining + */ + public CompilerStorage setStreamReader(StreamReader streamReader) { + storage.setStreamReader(streamReader); + return this; + } + + /** + * Sets the stream reader to be used for reading and storing values in storage + * @param The data format expected to be read or stored + * @param streamEditor The stream editor to be selected + * @return This object for method chaining + */ + public CompilerStorage setStreamEditor(StreamEditor streamEditor) { + storage.setStreamEditor(streamEditor); + return this; + } + + //#endregion + + //#region ConvenienceMethods + + /** + * Sets the file reader to be used for reading and storing values in storage. + * An equvalent method to setStreamWriter(StreamWriter streamWriter) + * @param The data format expected to be writen + * @param fileWriter The file writer to be selected + * @return This object for method chaining + */ + public CompilerStorage setFileWriter(StreamWriter fileWriter) { + storage.setStreamWriter(fileWriter); + return this; + } + + /** + * Sets the file reader to be used for reading values from storage. + * An equvalent method to setStreamReader(StreamReader streamReader) + * @param The data format expected to be writen + * @param fileReader The file reader to be selected + * @return This object for method chaining + */ + public CompilerStorage setFileReader(StreamReader fileReader) { + storage.setStreamReader(fileReader); + return this; + } + + /** + * Sets the stream reader to be used for reading and storing values in storage. + * An equvalent method to setStreamEditor(StreamEditor streamEditor) + * @param The data format expected to be read or stored + * @param fileEditor The stream editor to be selected + * @return This object for method chaining + */ + public CompilerStorage setFileEditor(StreamEditor fileEditor) { + storage.setStreamEditor(fileEditor); + return this; + } + + //#endregion + + //#region StreamStorage + + /** + * Stores the given compiler to the given output stream, converting the compiler using the specified formatter to produce a storable data format + * @param The data format to be used for storage + * @param compiler The compiler to be stored + * @param formatter The formatter to be used to convert values for storage. Only set for execution of this function. Use setFormatter to use this for multiple executions. + * @param outputStream The stream to be used + * @throws StoreFailureException + * @throws FormattingException + * @throws StorageFormatMismatchException + * @throws NullStorageObjectException + */ + public void convertAndStore(StorableCustomCompiler compiler, ValueFormatter formatter, OutputStream outputStream) throws StoreFailureException, FormattingException, StorageFormatMismatchException, NullStorageObjectException { + storage.convertAndStore(compiler, formatter, outputStream); + } + + /** + * Stores a specified compiler in the given output stream + * @param compiler The compiler to be stored + * @param outputStream The stream to be used + * @throws StoreFailureException + * @throws FormattingException + * @throws StorageFormatMismatchException + * @throws NullStorageObjectException + */ + public void store(StorableCustomCompiler compiler, OutputStream outputStream) throws StoreFailureException, FormattingException, StorageFormatMismatchException, NullStorageObjectException { + storage.store(compiler, outputStream); + } + + /** + * Reads a value from the given input stream, converts the value using the chosen formatter and loads it into the given compiler + * @param compiler An existing to load the value into + * @param inputStream The input stream to be read + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public void convertAndLoadInto(Loadable compiler, InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + storage.convertAndLoadInto(compiler, inputStream); + } + + /** + * Reads a value from the given input stream, converts the value using the provided formatter and loads it into the given compiler + * @param The expected value format to be read and provided to the formatter + * @param compiler The compiler to load the value into + * @param formatter The formatter to be used to convert data from the stream + * @param inputStream The input stream to be read + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public void convertAndLoadInto(Loadable compiler, ValueFormatter formatter, InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + storage.convertAndLoadInto(compiler, formatter, inputStream); + } + + /** + * Loads a compiler from the given input stream + * @param inputStream The input stream to read from + * @return The compiler built for the stream, once formatted by the chosen formatter + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public StorableCustomCompiler load(InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + StorageValue> storageValue = storage.load(inputStream); + return storableCustomCompilerFactory.produce(storageValue); + } + + //#endregion + + //#region FileStorage + + /** + * Stores the compiler in the targetted file + * @param compiler The compiler to be stored + * @throws UnsupportedValueException + * @throws UncheckedIOException + * @throws RuntimeException + * @throws UncheckedIOException + * @throws NullStorageObjectException + */ + public void store(StorableCustomCompiler compiler) throws UnsupportedValueException, UncheckedIOException, RuntimeException, UncheckedIOException, NullStorageObjectException { + storage.store(compiler); + } + + /** + * Stores the compiler in the given file + * @param compiler The compiler to be stored + * @param filePath The target file to use for storage + * @throws UnsupportedValueException + * @throws UncheckedIOException + * @throws RuntimeException + * @throws UncheckedIOException + * @throws NullStorageObjectException + */ + public void store(StorableCustomCompiler compiler, String filePath) throws UnsupportedValueException, UncheckedIOException, RuntimeException, UncheckedIOException, NullStorageObjectException { + storage.store(compiler, filePath); + } + + + /** + * Loads a compiler from the chosen file + * @return The loaded compiler + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + * @throws UncheckedIOException + */ + public StorableCustomCompiler load() throws LoadFailureException, FormatParseException, StorageFormatMismatchException, UncheckedIOException { + StorageValue> storageValue = storage.load(); + return storableCustomCompilerFactory.produce(storageValue); + } + + /** + * Loads a value from the chosen file into the given compiler + * @param compiler An existing compiler to load stored values into + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + * @throws UncheckedIOException + */ + public void loadInto(Loadable compiler) throws LoadFailureException, FormatParseException, StorageFormatMismatchException, UncheckedIOException { + storage.loadInto(compiler); + } + + //#endregion + + // TODO: Implement and test LoadableBy + +} diff --git a/src/main/java/component_construction/storable/StorableCustomCompiler.java b/src/main/java/component_construction/storable/StorableCustomCompiler.java new file mode 100644 index 0000000..bfcdf7b --- /dev/null +++ b/src/main/java/component_construction/storable/StorableCustomCompiler.java @@ -0,0 +1,61 @@ +package component_construction.storable; + +import java.util.Map; + +import code_generation.CodeGenerator; +import component_construction.custom_components.*; +import component_construction.storable.dynamic_loading.LoadableBy; +import component_construction.storable.exceptions.NonStorableComponentException; +import component_construction.storable.factories.StorableCustomCompilerFactory; +import component_construction.storable.StorableCustomCompiler; +import lexical_analysis.LexicalAnalyser; +import storage.external_interfaces.Storable; +import storage.storage_values.*; +import syntax_analysis.SyntaxAnalyser; + +public class StorableCustomCompiler extends CustomCompiler implements Storable, LoadableBy { + + /** + * Creates a new StorableCustomCompiler. All components must implement Storable. + * @param lexicalAnalyser A Storable LexicalAnalyser for this compiler + * @param syntaxAnalyser A Storable SyntaxAnalyser for this compiler + * @param codeGenerator A Storable CodeGenerator for this compiler + * @throws NonStorableComponentException A component was introduced without implementing Storable + */ + public StorableCustomCompiler( + LexicalAnalyser lexicalAnalyser, + SyntaxAnalyser syntaxAnalyser, + CodeGenerator codeGenerator + ) throws NonStorableComponentException { + super(lexicalAnalyser, syntaxAnalyser, codeGenerator); + + if (!(lexicalAnalyser instanceof Storable)) throw new NonStorableComponentException(lexicalAnalyser); + if (!(syntaxAnalyser instanceof Storable)) throw new NonStorableComponentException(syntaxAnalyser); + if (!(codeGenerator instanceof Storable)) throw new NonStorableComponentException(codeGenerator); + } + + @Override + public MapStorageValue getStorageRepresentation() { + return new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(lexicalAnalyser.getClass().getName()), + ((Storable)lexicalAnalyser).getStorageRepresentation() + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxAnalyser.getClass().getName()), + ((Storable)syntaxAnalyser).getStorageRepresentation() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGenerator.getClass().getName()), + ((Storable)codeGenerator).getStorageRepresentation() + ) + )); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof StorableCustomCompiler)) return false; + return super.equals(obj); + } + +} diff --git a/src/main/java/component_construction/storable/builders/StorableCustomCompilerBuilder.java b/src/main/java/component_construction/storable/builders/StorableCustomCompilerBuilder.java new file mode 100644 index 0000000..c5420c8 --- /dev/null +++ b/src/main/java/component_construction/storable/builders/StorableCustomCompilerBuilder.java @@ -0,0 +1,32 @@ +package component_construction.storable.builders; + +import component_construction.builders.CompilerBuilderTemplate; +import component_construction.storable.StorableCustomCompiler; +import component_construction.storable.exceptions.NonStorableComponentException; +import grammar_objects.GrammarParts; + +public class StorableCustomCompilerBuilder extends CompilerBuilderTemplate { + + @Override + protected StorableCustomCompilerBuilder getThis() { + return this; + } + + @Override + public StorableCustomCompiler createCompiler() throws NonStorableComponentException { + checkForCompleteBuild(); + + GrammarParts parts = grammar.getParts(); + + return new StorableCustomCompiler( + lexicalAnalyserFactory.produceAnalyser( + whitespaceDelimiters, + stronglyReservedWords, + weaklyReservedWords, + dynamicTokenRegex + ), + syntaxAnalyserFactory.produceAnalyser(parts), + codeGeneratorFactory.produceGenerator(ruleConvertor) + ); + } +} diff --git a/src/main/java/component_construction/storable/dynamic_loading/LoadableBy.java b/src/main/java/component_construction/storable/dynamic_loading/LoadableBy.java new file mode 100644 index 0000000..f9e3839 --- /dev/null +++ b/src/main/java/component_construction/storable/dynamic_loading/LoadableBy.java @@ -0,0 +1,51 @@ +package component_construction.storable.dynamic_loading; + +import java.lang.reflect.*; + +import component_construction.storable.exceptions.IncorrectlyFormattedException; + +/** + * A class specifying a designated loader for the current class. + * Loaders will be loaded using reflection. + * @param The concrete Loader class + */ +public interface LoadableBy> { + + /** + * Gets the {@code Loader} referenced by a given {@code LoadableBy} object + * @param The object type that may be loaded through the referenced {@code Loader} type + * @param The type of {@code Loader} referenced by this {@code LoadableBy} object + * @param loadableByClass The class implementing {@code LoadableBy} + * @return The class of the referenced {@code Loader} type + * @throws IllegalArgumentException The provided class does not directly implement {@code LoadableBy} + * @throws IncorrectlyFormattedException The provided {@code Loader} type is not a constructable/concrete {@code Class} object + */ + @SuppressWarnings("unchecked") + public static > Class getTargetLoader(Class extends LoadableBy> loadableByClass) throws IllegalArgumentException, IncorrectlyFormattedException { + ParameterizedType loadableByInterface = null; + + for (Type currentInterface : loadableByClass.getGenericInterfaces()) { + if (!(currentInterface instanceof ParameterizedType)) continue; + + ParameterizedType paramType = (ParameterizedType) currentInterface; + if (!paramType.getRawType().equals(LoadableBy.class)) continue; + + loadableByInterface = paramType; + break; + } + + if (loadableByInterface == null) + throw new IllegalArgumentException("Class " + loadableByClass.getName() + " does not directly implement LoadableBy."); + + Type actualTypeArgument = loadableByInterface.getActualTypeArguments()[0]; + + if (actualTypeArgument instanceof ParameterizedType) + throw new IncorrectlyFormattedException("Class " + loadableByClass.getName() + " provides a nested generic loader (" + actualTypeArgument.getTypeName() + "). Loaders must be direct, concrete Class objects."); + + if (!(actualTypeArgument instanceof Class)) + throw new IncorrectlyFormattedException("Class " + loadableByClass.getName() + " provides an abstract or unbound type token (" + actualTypeArgument.getTypeName() + "). The loader must be a direct, concrete Class object."); + + return (Class) actualTypeArgument; + } + +} diff --git a/src/main/java/component_construction/storable/dynamic_loading/Loader.java b/src/main/java/component_construction/storable/dynamic_loading/Loader.java new file mode 100644 index 0000000..dd13bce --- /dev/null +++ b/src/main/java/component_construction/storable/dynamic_loading/Loader.java @@ -0,0 +1,42 @@ +package component_construction.storable.dynamic_loading; + +import java.lang.reflect.InvocationTargetException; + +import component_construction.storable.exceptions.MissingEmptyConstructorException; +import component_construction.storable.factories.Factory; + +/** + * An interface defining the ability construct objects of the specified type + * @param The type of object to be constructed + */ +public interface Loader extends Factory { + + /** + * Constructs a new object of the specified {@code Loader} + * @param The type of object constructable by the {@code Loader} + * @param loaderClass The class of the {@code Loader} to be reflectively constructed + * @return An object of the specified {@code Loader} + * @throws MissingEmptyConstructorException The {@code Loader} did not contain the required empty constructor + * @throws IllegalArgumentException The specified {@code Loader} could not be constructed as it is either abstract or the constructor is inaccessible + */ + public static Loader construct(Class> loaderClass) throws MissingEmptyConstructorException, IllegalArgumentException { + try { + return loaderClass + .getConstructor() + .newInstance(); + } + catch (NoSuchMethodException e) { + throw new MissingEmptyConstructorException(loaderClass); + } + catch ( + InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException + e + ) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/src/main/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructor.java b/src/main/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructor.java new file mode 100644 index 0000000..e9ccfdf --- /dev/null +++ b/src/main/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructor.java @@ -0,0 +1,128 @@ +package component_construction.storable.dynamic_loading; + +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.stream.Collectors; + +public class ReflectiveClassConstructor { + + /** + * Constructs an object of the specified name and returns it as the target type, using reflection. + * @param The output target type + * @param className The name of the class to be loaded. Provided following the format provided by {@code someObject.class.getName()} + * @param targetType The specified target output type + * @return The constructed object of the target type + * @throws ClassNotFoundException The specified class could not be found + * @throws IllegalArgumentException One or more of the provided arguments has caused a failure to construct the specifed class + */ + public T construct( + String className, + Class targetType + ) + throws + ClassNotFoundException, + IllegalArgumentException + { + return construct( + className, + targetType, + new Class>[] {}, + new Object[] {} + ); + } + + /** + * Constructs an object of the specified name and returns it as the target type, using reflection. + * @param The output target type + * @param className The name of the class to be loaded. Provided following the format provided by {@code someObject.class.getName()} + * @param targetType The specified target output type + * @param parameterType The type expected by the constructor for the specified class + * @param parameter The value to be passed to the constructor of the specified class. Note: Inner classes require an additional initial parameter to be a parent object of the outer class + * @return The constructed object of the target type + * @throws ClassNotFoundException The specified class could not be found + * @throws IllegalArgumentException One or more of the provided arguments has caused a failure to construct the specifed class + */ + public T construct( + String className, + Class targetType, + Class> parameterType, + Object parameter + ) + throws + ClassNotFoundException, + IllegalArgumentException + { + return construct( + className, + targetType, + new Class>[] { parameterType }, + new Object[] { parameter } + ); + } + + /** + * Constructs an object of the specified name and returns it as the target type, using reflection. + * @param The output target type + * @param className The name of the class to be loaded. Provided following the format provided by {@code someObject.class.getName()} + * @param targetType The specified target output type + * @param parameterTypes The types expected by the constructor for the specified class + * @param parameters The values to be passes to the constructor of the specified class. Note: Inner classes require an additional initial parameter to be a parent object of the outer class + * @return The constructed object of the target type + * @throws ClassNotFoundException The specified class could not be found + * @throws IllegalArgumentException One or more of the provided arguments has caused a failure to construct the specifed class + */ + public T construct( + String className, + Class targetType, + Class>[] parameterTypes, + Object[] parameters + ) + throws + ClassNotFoundException, + IllegalArgumentException + { + try { + return Class + .forName(className) + .asSubclass(targetType) + .getDeclaredConstructor(parameterTypes) + .newInstance(parameters); + } + catch (ClassNotFoundException e) { + throw new ClassNotFoundException("Target class not found: " + className, e); + } + catch (NoSuchMethodException e) { + throw new IllegalArgumentException( + "No constructor found in " + className + " matching types: [" + getTypesString(parameterTypes) + "]", + e + ); + } + catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "Type mismatch between declared types [" + getTypesString(parameterTypes) + "] and parameter types [" + getParameterTypesString(parameters) + "]", + e + ); + } + catch (IllegalAccessException e) { + throw new IllegalArgumentException("Constructor is private or inaccessible in class: " + className, e); + } + catch (InstantiationException e) { + throw new IllegalArgumentException("Cannot instantiate abstract class or interface: " + className, e); + } + catch (InvocationTargetException e) { + throw new IllegalArgumentException("The constructor for " + className + " threw an exception", e.getCause()); + } + } + + protected String getTypesString(Class>[] parameterTypes) { + return Arrays.stream(parameterTypes) + .map(Class::getSimpleName) + .collect(Collectors.joining(", ")); + } + + protected String getParameterTypesString(Object[] parameters) { + return Arrays.stream(parameters) + .map(parameter -> parameter.getClass().getSimpleName()) + .collect(Collectors.joining(", ")); + } +} diff --git a/src/main/java/component_construction/storable/dynamic_loading/ReflectivelyLoadable.java b/src/main/java/component_construction/storable/dynamic_loading/ReflectivelyLoadable.java new file mode 100644 index 0000000..0e61c86 --- /dev/null +++ b/src/main/java/component_construction/storable/dynamic_loading/ReflectivelyLoadable.java @@ -0,0 +1,8 @@ +package component_construction.storable.dynamic_loading; + +import storage.external_interfaces.Loadable; + +/** + * Classes of this type must have a constructor that may be used to reflectively construct objects. + */ +public interface ReflectivelyLoadable extends Loadable {} \ No newline at end of file diff --git a/src/main/java/component_construction/storable/exceptions/ComponentCastException.java b/src/main/java/component_construction/storable/exceptions/ComponentCastException.java new file mode 100644 index 0000000..4cb2bc8 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/ComponentCastException.java @@ -0,0 +1,11 @@ +package component_construction.storable.exceptions; + +public class ComponentCastException extends RuntimeException { + + public ComponentCastException(String componentClassName, String expectedType, Throwable cause) { + super( + "The provided component class \"" + componentClassName + "\" could not be cast to the expected type \"" + expectedType + "\". Ensure \"" + componentClassName + "\" implements \"" + expectedType + "\".", + cause + ); + } +} diff --git a/src/main/java/component_construction/storable/exceptions/IncorrectLoadValueFormat.java b/src/main/java/component_construction/storable/exceptions/IncorrectLoadValueFormat.java new file mode 100644 index 0000000..27b7b63 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/IncorrectLoadValueFormat.java @@ -0,0 +1,11 @@ +package component_construction.storable.exceptions; + +public class IncorrectLoadValueFormat extends RuntimeException { + + public IncorrectLoadValueFormat(String expectedFormat, String actualFormat, Throwable cause) { + super( + "A load value was provided in an incorrect format. Expected - " + expectedFormat + ", Actual - " + actualFormat, + cause + ); + } +} diff --git a/src/main/java/component_construction/storable/exceptions/IncorrectlyFormattedException.java b/src/main/java/component_construction/storable/exceptions/IncorrectlyFormattedException.java new file mode 100644 index 0000000..5890745 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/IncorrectlyFormattedException.java @@ -0,0 +1,8 @@ +package component_construction.storable.exceptions; + +public class IncorrectlyFormattedException extends RuntimeException { + + public IncorrectlyFormattedException(String message) { + super(message); + } +} diff --git a/src/main/java/component_construction/storable/exceptions/MissingEmptyConstructorException.java b/src/main/java/component_construction/storable/exceptions/MissingEmptyConstructorException.java new file mode 100644 index 0000000..c143e05 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/MissingEmptyConstructorException.java @@ -0,0 +1,10 @@ +package component_construction.storable.exceptions; + +import component_construction.storable.dynamic_loading.Loader; + +public class MissingEmptyConstructorException extends RuntimeException { + + public MissingEmptyConstructorException(Class> loaderClass) { + super("The specified Loaded \"" + loaderClass.getName() + "\" is missing a required default/empty constructor"); + } +} diff --git a/src/main/java/component_construction/storable/exceptions/MissingKeyException.java b/src/main/java/component_construction/storable/exceptions/MissingKeyException.java new file mode 100644 index 0000000..127d341 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/MissingKeyException.java @@ -0,0 +1,26 @@ +package component_construction.storable.exceptions; + +import java.util.Collection; +import java.util.stream.Collectors; + +public class MissingKeyException extends RuntimeException { + public Collection missingKeys; + + public MissingKeyException(Collection missingKeys) { + super(); + this.missingKeys = missingKeys; + } + + @Override + public String getMessage() { + if (missingKeys.size() == 1) + return "The key \"" + missingKeys.iterator().next() + "\" is missing"; + + String missingKeysString = missingKeys + .stream() + .map(value -> "\"" + value + "\"") + .collect(Collectors.joining(", ")); + + return "The keys " + missingKeysString + " are missing"; + } +} diff --git a/src/main/java/component_construction/storable/exceptions/NonExistentComponentException.java b/src/main/java/component_construction/storable/exceptions/NonExistentComponentException.java new file mode 100644 index 0000000..2652ce3 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/NonExistentComponentException.java @@ -0,0 +1,11 @@ +package component_construction.storable.exceptions; + +public class NonExistentComponentException extends RuntimeException { + + public NonExistentComponentException(String attemptedComponentClassName, Throwable cause) { + super( + "The component class \"" + attemptedComponentClassName + "\" could not be found or does not exist. Check the provided component name correctly references the intended class.", + cause + ); + } +} diff --git a/src/main/java/component_construction/storable/exceptions/NonStorableComponentException.java b/src/main/java/component_construction/storable/exceptions/NonStorableComponentException.java new file mode 100644 index 0000000..44929d7 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/NonStorableComponentException.java @@ -0,0 +1,11 @@ +package component_construction.storable.exceptions; + +import storage.external_interfaces.Storable; + +public class NonStorableComponentException extends RuntimeException { + + public NonStorableComponentException(Object component) { + super("The selected component \"" + component.getClass().getName() + "\" must implement " + Storable.class.getSimpleName()); + } + +} diff --git a/src/main/java/component_construction/storable/exceptions/ReflectiveLoadFailure.java b/src/main/java/component_construction/storable/exceptions/ReflectiveLoadFailure.java new file mode 100644 index 0000000..6685d55 --- /dev/null +++ b/src/main/java/component_construction/storable/exceptions/ReflectiveLoadFailure.java @@ -0,0 +1,9 @@ +package component_construction.storable.exceptions; + +public class ReflectiveLoadFailure extends RuntimeException { + + public ReflectiveLoadFailure(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/component_construction/storable/factories/Factory.java b/src/main/java/component_construction/storable/factories/Factory.java new file mode 100644 index 0000000..892b688 --- /dev/null +++ b/src/main/java/component_construction/storable/factories/Factory.java @@ -0,0 +1,11 @@ +package component_construction.storable.factories; + +import storage.storage_values.StorageValue; + +/** + * A class for objects which may produce other objects from a specified {@code StorageValue} + * @param The type of object to be produced + */ +public interface Factory { + public T produce(StorageValue> loadValue); +} \ No newline at end of file diff --git a/src/main/java/component_construction/storable/factories/StorableCustomCompilerFactory.java b/src/main/java/component_construction/storable/factories/StorableCustomCompilerFactory.java new file mode 100644 index 0000000..9a01a72 --- /dev/null +++ b/src/main/java/component_construction/storable/factories/StorableCustomCompilerFactory.java @@ -0,0 +1,236 @@ +package component_construction.storable.factories; + +import java.util.*; + +import code_generation.CodeGenerator; +import component_construction.storable.StorableCustomCompiler; +import component_construction.storable.dynamic_loading.*; +import component_construction.storable.exceptions.*; +import component_construction.storable.factories.Factory; +import lexical_analysis.LexicalAnalyser; +import storage.storage_values.*; +import syntax_analysis.SyntaxAnalyser; + +/** + * A factory for producing StorableCustomCompilers. + */ +public class StorableCustomCompilerFactory implements Loader { + protected ReflectiveClassConstructor reflectiveClassLoader = new ReflectiveClassConstructor(); + protected Map> lexicalAnalyserFactoryRepository = new HashMap<>(); + protected Map> syntaxAnalyserFactoryRepository = new HashMap<>(); + protected Map> codeGeneratorFactoryRepository = new HashMap<>(); + protected final Set expectedKeys = Set.of( + "lexicalAnalyser", + "syntaxAnalyser", + "codeGenerator" + ); + + public StorableCustomCompilerFactory addLexicalAnalyserFactory(String name, Factory factory) { + lexicalAnalyserFactoryRepository.put(name, factory); + return this; + } + + public StorableCustomCompilerFactory addSyntaxAnalyserFactory(String name, Factory factory) { + syntaxAnalyserFactoryRepository.put(name, factory); + return this; + } + + public StorableCustomCompilerFactory addCodeGeneratorFactory(String name, Factory factory) { + codeGeneratorFactoryRepository.put(name, factory); + return this; + } + + @Override + /** + * Builds a {@code StorableCustomCompiler} from a map of specified StorageValues. + * + * The format of the loadValue for loading {@code StorableCustomCompiler} components is a {@code MapStorageValue} containing the keys "lexicalAnalyser", "syntaxAnalyser", and "codeGenerator" mapped to their respective {@code StorageValue>} descriptions + * + * In order to be loadable, components must be one of: + * - registered with a factory + * - {@code LoadableBy} + * - {@code Loadable} + * - Have a constructor taking a single {@code StorageValue>} parameter + * @param loadValue The StorageValue to be used for building a {@code StorableCustomCompiler} + * @return The produced {@code StorableCustomCompiler} + * @throws IncorrectLoadValueFormat The provided load value was in an incorrect format + * @throws MissingKeyException The provided load value was missing one or more required keys + * @throws NonExistentComponentException A specified component class does not exist + * @throws ComponentCastException A specified component class could not be cast to its intended type + * @throws ReflectiveLoadFailure A specified component class does not contain a constructor taing a single {@code StorageValue>} parameter + * @throws IncorrectLoadValueFormat A provided component's description was not the expected type {@code ListStorageValue} + * @throws NonStorableComponentException A pecified component class does not implement Storable + */ + public StorableCustomCompiler produce(StorageValue> loadValue) throws + IncorrectLoadValueFormat, + MissingKeyException, + NonExistentComponentException, + ComponentCastException, + ReflectiveLoadFailure, + NonStorableComponentException + { + Map> mapValue = tryGetMapValue(loadValue); + Set keys = mapValue.keySet(); + + if (!keys.containsAll(expectedKeys)) { + Set missingKeys = new HashSet(expectedKeys); + missingKeys.removeAll(keys); + throw new MissingKeyException(missingKeys); + } + + return new StorableCustomCompiler( + buildComponent( + lexicalAnalyserFactoryRepository, + mapValue.get("lexicalAnalyser"), + LexicalAnalyser.class + ), + buildComponent( + syntaxAnalyserFactoryRepository, + mapValue.get("syntaxAnalyser"), + SyntaxAnalyser.class + ), + buildComponent( + codeGeneratorFactoryRepository, + mapValue.get("codeGenerator"), + CodeGenerator.class + ) + ); + } + + private Map> tryGetMapValue(StorageValue> loadValue) throws IncorrectLoadValueFormat { + MapStorageValue map; + Map> mapValue; + + try { + map = (MapStorageValue) loadValue; + } + catch (ClassCastException e) { + throw new IncorrectLoadValueFormat( + "MapStorageValue which maps String to ListStorageValue", + loadValue.getClass().getSimpleName(), + e + ); + } + + mapValue = map.getValue(); + return mapValue; + } + + /** + * Converts a given description into a {@code ComponentInformation} object + * @param description The component's description as a {@code ListStorageValue} + * @return The ComponentInformation representation of the description + * @throws IncorrectLoadValueFormat The provided component description was not the expected type {@code ListStorageValue} + */ + protected ComponentInformation getComponentDescription(StorageValue> description) throws IncorrectLoadValueFormat { + List> entry; + + try { + entry = ((ListStorageValue)description).getValue(); + } + catch (ClassCastException e) { + throw new IncorrectLoadValueFormat( + "MapStorageValue which maps String to ListStorageValue", + "MapStorageValue which maps String to " + description.getClass().getSimpleName(), + e + ); + } + + return new ComponentInformation( + ((StringStorageValue)entry.get(0)).getValue(), + entry.get(1) + ); + } + + protected record ComponentInformation(String name, StorageValue> description) {} + + @SuppressWarnings("unchecked") + /** + * Builds a component with the provided description. + * Components must be: registered with a factory; LoadableBy; Loadable; Or, have a constructor taking a single {@code StorageValue>} parameter. + * @param The abstract type of the component + * @param repository The repository to query for registered factories for the specific component type + * @param description The description with which to load the component with + * @param selectedType The subclass with which to produce and use the component + * @return The built component + * @throws NonExistentComponentException The specified component class does not exist + * @throws ComponentCastException The specified component class could not be cast to the selectedType + * @throws ReflectiveLoadFailure The specified component class does not contain a constructor taing a single {@code StorageValue>} parameter + * @throws IncorrectLoadValueFormat The provided component description was not the expected type {@code ListStorageValue} + */ + protected T buildComponent( + Map> repository, + StorageValue> description, + Class selectedType + ) throws + NonExistentComponentException, + ComponentCastException, + ReflectiveLoadFailure, + IncorrectLoadValueFormat + { + ComponentInformation componentDescription = getComponentDescription(description); + + if (repository.containsKey(componentDescription.name())) + return repository + .get(componentDescription.name()) + .produce(componentDescription.description()); + + Class clazz; + + try { + clazz = (Class) Class + .forName(componentDescription.name()) + .asSubclass(selectedType); + } + catch (ClassNotFoundException e) { + throw new NonExistentComponentException(componentDescription.name(), e); + } + catch (ClassCastException e) { + throw new ComponentCastException(componentDescription.name(), selectedType.getName(), e); + } + + if (LoadableBy.class.isAssignableFrom(clazz)) { + Class>> loadableBy = (Class>>) clazz.asSubclass(LoadableBy.class); + Class> targetLoader = LoadableBy.getTargetLoader(loadableBy); + Loader loader = Loader.construct(targetLoader); + return loader.produce(componentDescription.description()); + } + + if (ReflectivelyLoadable.class.isAssignableFrom(clazz)) { + T component; + + try { + component = reflectiveClassLoader.construct( + componentDescription.name(), + selectedType + ); + } + catch (ClassNotFoundException | IllegalArgumentException e) { + // ClassNotFoundException cannot occur as the cast succeeded earlier in this method + // There are also no arguments to cause an IllegalArgumentException + return null; + } + + ((ReflectivelyLoadable)component).load(componentDescription.description()); + + return component; + } + + // Use constructor + try { + return reflectiveClassLoader.construct( + componentDescription.name(), + selectedType, + StorageValue.class, + componentDescription.description() + ); + } + catch (ClassNotFoundException e) { + // ClassNotFoundException cannot occur as the cast succeeded earlier in this method + return null; + } + catch (IllegalArgumentException e) { + throw new ReflectiveLoadFailure("Failed to construct an object of class \"" + componentDescription.name() + "\" as no constructor exists taking \"StorageValue>\" as its only parameter.", e); + } + } +} diff --git a/src/main/java/helper_objects/TypeReference.java b/src/main/java/helper_objects/TypeReference.java new file mode 100644 index 0000000..9b2b9d1 --- /dev/null +++ b/src/main/java/helper_objects/TypeReference.java @@ -0,0 +1,29 @@ +package helper_objects; + +import java.lang.reflect.*; + +/** + * A class for holding compile-time type information during runtime. + * Implementation of the "Type Token" design pattern. + */ +public abstract class TypeReference { + private Type type; + + private TypeReference() { + Type superClass = getClass().getGenericSuperclass(); + this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } + + @SuppressWarnings("unchecked") + public Class getContainedClass() { + return (Class) type.getClass(); + } + + public static TypeReference instantiate() { + return new TypeReference() {}; + } +} diff --git a/src/main/java/helper_objects/ValueEnum.java b/src/main/java/helper_objects/ValueEnum.java new file mode 100644 index 0000000..74baf21 --- /dev/null +++ b/src/main/java/helper_objects/ValueEnum.java @@ -0,0 +1,5 @@ +package helper_objects; + +public interface ValueEnum { + public T getValue(); +} diff --git a/src/main/java/storage/Storage.java b/src/main/java/storage/Storage.java new file mode 100644 index 0000000..42b8ad8 --- /dev/null +++ b/src/main/java/storage/Storage.java @@ -0,0 +1,493 @@ +package storage; + +import java.io.*; +import java.lang.reflect.ParameterizedType; +import java.nio.file.Path; + +import helper_objects.TypeReference; +import storage.exceptions.*; +import storage.file_editors.*; +import storage.external_interfaces.*; +import storage.storage_value_adapters.UnsupportedValueException; +import storage.storage_values.StorageValue; +import storage.value_formatters.*; + +/** + * A utility class for storage + */ +public class Storage { + + private Path targetFilepath = Path.of("." + File.separator + "storageFile.txt"); + private ChosenFormatter> formatter = new ChosenFormatter<>(new ValueToStringFormatter()); + private ChosenStreamWriter> streamWriter = new ChosenStreamWriter<>(new DefaultUTF8StreamEditor()); + private ChosenStreamReader> streamReader = new ChosenStreamReader<>(new DefaultUTF8StreamEditor()); + + //#region Constructors + + public Storage() {} + + //#endregion + + //#region Getters + + /** + * Gets the currently tagetted filepath being used for storage + * @return The targeted filepath + */ + public Path getTargetFilepath() { + return targetFilepath; + } + + //#endregion + + //#region Configuration + + /** + * Sets the target filepath the be use for storage + * @param filepath The filepath to target + * @return This Storage object for method chaining + */ + public Storage setTargetPath(Path filepath) { + targetFilepath = filepath; + return this; + } + + /** + * Sets the target filepath the be use for storage + * @param filepath The absolute filepath to be targeted + * @return This Storage object for method chaining + */ + public Storage setAbsoluteTargetPath(String filepath) { + targetFilepath = Path.of(filepath); + return this; + } + + /** + * Sets the target filepath the be use for storage + * @param filepath The relative filepath to be targeted + * @return This Storage object for method chaining + */ + public Storage setRelativeTargetPath(String filepath) { + targetFilepath = Path.of("." + File.separator + filepath); + return this; + } + + /** + * Sets the formatter to be used for converting StorageValues into storage representations + * @param The target format to convert values to/from + * @param formatter The formatter to be used + * @return This Storage object for method chaining + */ + public Storage setFormatter(ValueFormatter formatter) { + this.formatter = new ChosenFormatter(formatter); + return this; + } + + /** + * Sets the stream writer to be used for storing storage values + * @param The data format expected to be writen + * @param streamWriter The stream writer to be selected + * @return This Storage object for method chaining + */ + public Storage setStreamWriter(StreamWriter streamWriter) { + this.streamWriter = new ChosenStreamWriter<>(streamWriter); + return this; + } + + /** + * Sets the stream reader to be used for reading values from storage + * @param The data format expected to be output when read + * @param streamReader The stream reader to be selected + * @return This Storage object for method chaining + */ + public Storage setStreamReader(StreamReader streamReader) { + this.streamReader = new ChosenStreamReader<>(streamReader); + return this; + } + + /** + * Sets the stream reader to be used for reading and storing values in storage + * @param The data format expected to be read or stored + * @param streamEditor The stream editor to be selected + * @return This Storage object for method chaining + */ + public Storage setStreamEditor(StreamEditor streamEditor) { + this.streamWriter = new ChosenStreamWriter<>(streamEditor); + this.streamReader = new ChosenStreamReader<>(streamEditor); + return this; + } + + //#endregion + + //#region ConvenienceMethods + + /** + * Sets the file reader to be used for reading and storing values in storage. + * An equvalent method to setStreamWriter(StreamWriter streamWriter) + * @param The data format expected to be writen + * @param fileWriter The file writer to be selected + * @return This Storage object for method chaining + */ + public Storage setFileWriter(StreamWriter fileWriter) { + return setStreamWriter(fileWriter); + } + + /** + * Sets the file reader to be used for reading values from storage. + * An equvalent method to setStreamReader(StreamReader streamReader) + * @param The data format expected to be writen + * @param fileReader The file reader to be selected + * @return This Storage object for method chaining + */ + public Storage setFileReader(StreamReader fileReader) { + return setStreamReader(fileReader); + } + + /** + * Sets the stream reader to be used for reading and storing values in storage. + * An equvalent method to setStreamEditor(StreamEditor streamEditor) + * @param The data format expected to be read or stored + * @param fileEditor The stream editor to be selected + * @return This Storage object for method chaining + */ + public Storage setFileEditor(StreamEditor fileEditor) { + return setStreamEditor(fileEditor); + } + + //#endregion + + //#region StreamStorage + + /** + * Stores the given object to the given output stream, converting the object using the specified formatter to produce a storable data format + * @param The data format to be used for storage + * @param storageObject The object to be stored + * @param formatter The formatter to be used to convert values for storage. Only set for execution of this function. Use setFormatter to use this for multiple executions. + * @param outputStream The stream to be used + * @throws StoreFailureException + * @throws FormattingException + * @throws StorageFormatMismatchException + * @throws NullStorageObjectException + */ + public void convertAndStore(Storable storageObject, ValueFormatter formatter, OutputStream outputStream) throws StoreFailureException, FormattingException, StorageFormatMismatchException, NullStorageObjectException { + if(storageObject == null) throw new NullStorageObjectException(); + + convertAndStore_Inner(storageObject.getStorageRepresentation(), new ChosenFormatter(formatter), streamWriter, outputStream); + } + + /** + * Stores the given object in the given output stream + * @param storageObject The object to be stored + * @param outputStream The stream to be used + * @throws StoreFailureException + * @throws FormattingException + * @throws StorageFormatMismatchException + * @throws NullStorageObjectException + */ + public void store(Storable storageObject, OutputStream outputStream) throws StoreFailureException, FormattingException, StorageFormatMismatchException, NullStorageObjectException { + if(storageObject == null) throw new NullStorageObjectException(); + + convertAndStore_Inner(storageObject.getStorageRepresentation(), formatter, streamWriter, outputStream); + } + + /** + * Reads a value from the given input stream, converts the value using the chosen formatter and loads it into the given object + * @param objectToLoad The object to load the value into + * @param inputStream The input stream to be read + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public void convertAndLoadInto(Loadable objectToLoad, InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + objectToLoad.load(load_Inner(inputStream, formatter, streamReader)); + } + + /** + * Reads a value from the given input stream, converts the value using the provided formatter and loads it into the given object + * @param The expected value format to be read and provided to the formatter + * @param objectToLoad The object to load the value into + * @param formatter The formatter to be used to convert data from the stream + * @param inputStream The input stream to be read + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public void convertAndLoadInto(Loadable objectToLoad, ValueFormatter formatter, InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + objectToLoad.load(load_Inner(inputStream, new ChosenFormatter(formatter), streamReader)); + } + + /** + * Loads a value from the given input stream + * @param inputStream The input stream to read from + * @return The value read from the stream, once formatted by the chosen formatter + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + public StorageValue> load(InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + return load_Inner(inputStream, formatter, streamReader); + } + + /** + * Loads a value from the given input stream and specifies the expected type + * @param The expected inner type of the returned storage value + * @param inputStream The input stream to be read + * @return The value read from the stream, once formatted by the chosen formatter + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + */ + @SuppressWarnings("unchecked") + public StorageValue loadWithType(InputStream inputStream) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + try { + return (StorageValue)load(inputStream); + } + catch (ClassCastException e) { + Class chosenType = TypeReference.instantiate().getContainedClass(); + + throw new ClassCastException( + "The format " + + chosenType.getSimpleName() + + " is inconsistant with the type " + + formatter.format.getSimpleName() + + " produced by the chosen formatter." + ); + } + } + + //#endregion + + //#region FileStorage + + /** + * Stores the given object in the targetted file + * @param storageObject The object to be stored + * @throws UnsupportedValueException + * @throws UncheckedIOException + * @throws RuntimeException + * @throws UncheckedIOException + * @throws NullStorageObjectException + */ + public void store(Storable storageObject) throws UnsupportedValueException, UncheckedIOException, RuntimeException, UncheckedIOException, NullStorageObjectException { + if(storageObject == null) throw new NullStorageObjectException(); + + usingTargetFileOutputStream( + (outputStream) -> convertAndStore_Inner(storageObject.getStorageRepresentation(), formatter, streamWriter, outputStream) + ); + } + + /** + * Stores the given object in the given file + * @param storageObject The object to be stored + * @param filePath The target file to use for storage + * @throws UnsupportedValueException + * @throws UncheckedIOException + * @throws RuntimeException + * @throws UncheckedIOException + * @throws NullStorageObjectException + */ + public void store(Storable storageObject, String filePath) throws UnsupportedValueException, UncheckedIOException, RuntimeException, UncheckedIOException, NullStorageObjectException { + if(storageObject == null) throw new NullStorageObjectException(); + + usingFileOutputStream( + new File(filePath), + (outputStream) -> convertAndStore_Inner(storageObject.getStorageRepresentation(), formatter, streamWriter, outputStream) + ); + } + + /** + * Stores the given object in the targetted file + * @param The type of storage value to be stored + * @param storageObject The object to be stored + * @throws StoreFailureException + * @throws FormattingException + * @throws StorageFormatMismatchException + * @throws UncheckedIOException + * @throws NullStorageObjectException + */ + public void store(StorageValue storageObject) throws StoreFailureException, FormattingException, StorageFormatMismatchException, UncheckedIOException, NullStorageObjectException { + if(storageObject == null) throw new NullStorageObjectException(); + + usingTargetFileOutputStream( + (outputStream) -> convertAndStore_Inner(storageObject, formatter, streamWriter, outputStream) + ); + } + + /** + * Loads a value from the chosen file + * @return The loaded value + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + * @throws UncheckedIOException + */ + public StorageValue> load() throws LoadFailureException, FormatParseException, StorageFormatMismatchException, UncheckedIOException { + return usingTargetFileInputStream( + (inputStream) -> load(inputStream) + ); + } + + /** + * Loads a value from the chosen file into the given object + * @param targetObject The object to load stored values into + * @throws LoadFailureException + * @throws FormatParseException + * @throws StorageFormatMismatchException + * @throws UncheckedIOException + */ + public void loadInto(Loadable targetObject) throws LoadFailureException, FormatParseException, StorageFormatMismatchException, UncheckedIOException { + targetObject.load(load()); + } + + //#endregion + + //#region StorageOperations + + private StorageValue> load_Inner(InputStream inputStream, ChosenFormatter> formatter, ChosenStreamReader> streamReader) throws LoadFailureException, FormatParseException, StorageFormatMismatchException { + checkForFormatMismatch(formatter, streamReader); + + Object format; + + try { + format = streamReader.readFrom(inputStream); + } + catch (Exception e) { + throw new LoadFailureException(e); + } + + try { + return formatter.parse(format); + } + catch (Exception e) { + throw new FormatParseException(e); + } + } + + private void convertAndStore_Inner(StorageValue> storageObject, ChosenFormatter> formatter, ChosenStreamWriter> streamWriter, OutputStream outputStream) throws StoreFailureException, FormattingException, StorageFormatMismatchException { + checkForFormatMismatch(formatter, streamWriter); + + Object format; + + try { + format = formatter.format(storageObject); + } + catch (Exception e) { + throw new FormattingException(e); + } + + try { + streamWriter.addTo(outputStream, format); + } catch (Exception e) { + throw new StoreFailureException(e); + } + } + + //#endregion + + //#region ComponentWrappers + + private abstract class FormatHolder { + public Class format; + + @SuppressWarnings("unchecked") + public FormatHolder(Object genericTarget) { + ParameterizedType targetType = (ParameterizedType)(genericTarget.getClass().getGenericInterfaces()[0]); + format = (Class)targetType.getActualTypeArguments()[0]; + } + } + + private class ChosenFormatter extends FormatHolder implements ValueFormatter { + ValueFormatter innerFormatter; + + public ChosenFormatter(ValueFormatter formatter) { + super(formatter); + innerFormatter = formatter; + } + + @Override + public F format(StorageValue> value) throws UnsupportedValueException { + return innerFormatter.format(value); + } + + @Override + public StorageValue> parse(Object formattedData) throws UnsupportedValueException { + F data = format.cast(formattedData); + return innerFormatter.parse(data); + } + } + + private class ChosenStreamWriter extends FormatHolder { + StreamWriter innerStreamWriter; + + public ChosenStreamWriter(StreamWriter streamWriter) { + super(streamWriter); + innerStreamWriter = streamWriter; + } + + public void addTo(OutputStream stream, Object contents) throws IOException, RuntimeException { + innerStreamWriter.addTo(stream, format.cast(contents)); + } + } + + private class ChosenStreamReader extends FormatHolder { + StreamReader innerStreamReader; + + public ChosenStreamReader(StreamReader streamReader) { + super(streamReader); + innerStreamReader = streamReader; + } + + public F readFrom(InputStream stream) throws IOException { + return innerStreamReader.readFrom(stream); + } + } + + //#endregion + + //#region Helpers + + private void checkForFormatMismatch(FormatHolder> holder1, FormatHolder> holder2) throws StorageFormatMismatchException { + if (holder1.format.equals(holder2.format)) return; + + throw new StorageFormatMismatchException( + holder1.format.getSimpleName(), + holder2.format.getSimpleName() + ); + } + + private interface OutputStreamReceiver { + void run(OutputStream outputStream); + } + + private interface InputStreamReceiver { + T run(InputStream inputStream); + } + + private void usingFileOutputStream(File file, OutputStreamReceiver function) throws UncheckedIOException { + try (FileOutputStream outputStream = new FileOutputStream(file)) { + function.run(outputStream); + } + catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private void usingTargetFileOutputStream(OutputStreamReceiver function) throws UncheckedIOException { + usingFileOutputStream(targetFilepath.toFile(), function); + } + + private T usingFileInputStream(File file, InputStreamReceiver function) throws UncheckedIOException { + try (FileInputStream inputStream = new FileInputStream(file)) { + return function.run(inputStream); + } + catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private T usingTargetFileInputStream(InputStreamReceiver function) throws UncheckedIOException { + return usingFileInputStream(targetFilepath.toFile(), function); + } + + //#endregion +} diff --git a/src/main/java/storage/exceptions/FormatParseException.java b/src/main/java/storage/exceptions/FormatParseException.java new file mode 100644 index 0000000..3092584 --- /dev/null +++ b/src/main/java/storage/exceptions/FormatParseException.java @@ -0,0 +1,9 @@ +package storage.exceptions; + +public class FormatParseException extends RuntimeException { + + public FormatParseException(Exception cause) { + super("An error occurred when attempting to parse formatted data.", cause); + } + +} diff --git a/src/main/java/storage/exceptions/FormattingException.java b/src/main/java/storage/exceptions/FormattingException.java new file mode 100644 index 0000000..99b08b3 --- /dev/null +++ b/src/main/java/storage/exceptions/FormattingException.java @@ -0,0 +1,9 @@ +package storage.exceptions; + +public class FormattingException extends RuntimeException { + + public FormattingException(Exception cause) { + super("An error occurred when attempting to format data for storage.", cause); + } + +} diff --git a/src/main/java/storage/exceptions/LoadFailureException.java b/src/main/java/storage/exceptions/LoadFailureException.java new file mode 100644 index 0000000..c4f2f55 --- /dev/null +++ b/src/main/java/storage/exceptions/LoadFailureException.java @@ -0,0 +1,9 @@ +package storage.exceptions; + +public class LoadFailureException extends RuntimeException { + + public LoadFailureException(Exception cause) { + super("An error occurred when attempting a load operation.", cause); + } + +} \ No newline at end of file diff --git a/src/main/java/storage/exceptions/NullStorageObjectException.java b/src/main/java/storage/exceptions/NullStorageObjectException.java new file mode 100644 index 0000000..b460783 --- /dev/null +++ b/src/main/java/storage/exceptions/NullStorageObjectException.java @@ -0,0 +1,9 @@ +package storage.exceptions; + +public class NullStorageObjectException extends RuntimeException { + + public NullStorageObjectException() { + super("The provided storage object was null. Enusre a valid Storable is provided."); + } + +} diff --git a/src/main/java/storage/exceptions/StorageFormatMismatchException.java b/src/main/java/storage/exceptions/StorageFormatMismatchException.java new file mode 100644 index 0000000..980fd4e --- /dev/null +++ b/src/main/java/storage/exceptions/StorageFormatMismatchException.java @@ -0,0 +1,14 @@ +package storage.exceptions; + +public class StorageFormatMismatchException extends RuntimeException { + + public StorageFormatMismatchException(String type1Name, String type2Name) { + super( + "The formatter and stream editor types were mismatched. Formatter - " + + type1Name.getClass().getSimpleName() + + ", Stream - " + + type2Name.getClass().getSimpleName() + ); + } + +} diff --git a/src/main/java/storage/exceptions/StoreFailureException.java b/src/main/java/storage/exceptions/StoreFailureException.java new file mode 100644 index 0000000..0515ea3 --- /dev/null +++ b/src/main/java/storage/exceptions/StoreFailureException.java @@ -0,0 +1,9 @@ +package storage.exceptions; + +public class StoreFailureException extends RuntimeException { + + public StoreFailureException(Exception cause) { + super("An error occurred when attempting a store operation.", cause); + } + +} \ No newline at end of file diff --git a/src/main/java/storage/external_interfaces/Loadable.java b/src/main/java/storage/external_interfaces/Loadable.java new file mode 100644 index 0000000..a69ebb9 --- /dev/null +++ b/src/main/java/storage/external_interfaces/Loadable.java @@ -0,0 +1,16 @@ +package storage.external_interfaces; + +import storage.storage_values.StorageValue; + +/** + * An interface denoting the state of this object may be loaded from a specified {@code StorageValue} + */ +public interface Loadable { + + /** + * Loads the given state into this object + * @param data The {@code StorageValue} state to be loaded + */ + public void load(StorageValue> data); + +} diff --git a/src/main/java/storage/external_interfaces/Storable.java b/src/main/java/storage/external_interfaces/Storable.java new file mode 100644 index 0000000..189ad0c --- /dev/null +++ b/src/main/java/storage/external_interfaces/Storable.java @@ -0,0 +1,16 @@ +package storage.external_interfaces; + +import storage.storage_values.StorageValue; + +/** + * An interface denoting that this object's state can be fetched + */ +public interface Storable { + + /** + * Gets the storage representation of this object + * @return A {@code StoraageValue} representing the storable state of this object + */ + public StorageValue> getStorageRepresentation(); + +} diff --git a/src/main/java/storage/file_editors/DefaultUTF8StreamEditor.java b/src/main/java/storage/file_editors/DefaultUTF8StreamEditor.java new file mode 100644 index 0000000..a18371a --- /dev/null +++ b/src/main/java/storage/file_editors/DefaultUTF8StreamEditor.java @@ -0,0 +1,22 @@ +package storage.file_editors; + +import java.io.*; +import java.nio.charset.StandardCharsets; + +public class DefaultUTF8StreamEditor implements StreamEditor { + + @Override + public String readFrom(InputStream stream) throws IOException { + try (stream) { + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Override + public void addTo(OutputStream stream, String contents) throws IOException { + try (stream) { + stream.write(contents.getBytes(StandardCharsets.UTF_8)); + } + } + +} diff --git a/src/main/java/storage/file_editors/StreamEditor.java b/src/main/java/storage/file_editors/StreamEditor.java new file mode 100644 index 0000000..454a994 --- /dev/null +++ b/src/main/java/storage/file_editors/StreamEditor.java @@ -0,0 +1,3 @@ +package storage.file_editors; + +public interface StreamEditor extends StreamReader, StreamWriter {} diff --git a/src/main/java/storage/file_editors/StreamReader.java b/src/main/java/storage/file_editors/StreamReader.java new file mode 100644 index 0000000..f63a314 --- /dev/null +++ b/src/main/java/storage/file_editors/StreamReader.java @@ -0,0 +1,7 @@ +package storage.file_editors; + +import java.io.*; + +public interface StreamReader { + public abstract T readFrom(InputStream stream) throws IOException; +} diff --git a/src/main/java/storage/file_editors/StreamWriter.java b/src/main/java/storage/file_editors/StreamWriter.java new file mode 100644 index 0000000..63ff81e --- /dev/null +++ b/src/main/java/storage/file_editors/StreamWriter.java @@ -0,0 +1,7 @@ +package storage.file_editors; + +import java.io.*; + +public interface StreamWriter { + public abstract void addTo(OutputStream stream, T contents) throws IOException; +} \ No newline at end of file diff --git a/src/main/java/storage/storage_value_adapters/StorageValueAdapter.java b/src/main/java/storage/storage_value_adapters/StorageValueAdapter.java new file mode 100644 index 0000000..d9e70cf --- /dev/null +++ b/src/main/java/storage/storage_value_adapters/StorageValueAdapter.java @@ -0,0 +1,13 @@ +package storage.storage_value_adapters; + +import storage.storage_values.StorageValue; + +/** + * An interface that defines an adapter converting StorageValues to a chosen representation for use within a StorageMethod + */ +public interface StorageValueAdapter { + + public E retreiveValue(StorageValue storageValue); + public StorageValue packageValue(E value); + +} diff --git a/src/main/java/storage/storage_value_adapters/UnsupportedValueException.java b/src/main/java/storage/storage_value_adapters/UnsupportedValueException.java new file mode 100644 index 0000000..a0fe439 --- /dev/null +++ b/src/main/java/storage/storage_value_adapters/UnsupportedValueException.java @@ -0,0 +1,18 @@ +package storage.storage_value_adapters; + +import storage.storage_values.StorageValue; + +public class UnsupportedValueException extends RuntimeException { + + public UnsupportedValueException(StorageValue value) { + super(value.getClass().toString() + " is not supported by this formatter."); + } + + public UnsupportedValueException() { + super( + "The input could not be parsed by this formatter.\n" + + "If the data was intended for this formatter, the data may be malformed." + + "Otherwise, Try a different formatter or develop a custom formatter for this data." + ); + } +} \ No newline at end of file diff --git a/src/main/java/storage/storage_values/IntegerStorageValue.java b/src/main/java/storage/storage_values/IntegerStorageValue.java new file mode 100644 index 0000000..2cc2738 --- /dev/null +++ b/src/main/java/storage/storage_values/IntegerStorageValue.java @@ -0,0 +1,13 @@ +package storage.storage_values; + +public class IntegerStorageValue extends StorageValue { + + public IntegerStorageValue(Integer integer) { + super(integer); + } + + @Override + public String toString() { + return "IntegerStorageValue(" + this.value + ")"; + } +} diff --git a/src/main/java/storage/storage_values/ListStorageValue.java b/src/main/java/storage/storage_values/ListStorageValue.java new file mode 100644 index 0000000..555ea7e --- /dev/null +++ b/src/main/java/storage/storage_values/ListStorageValue.java @@ -0,0 +1,27 @@ +package storage.storage_values; + +import java.util.*; + +public class ListStorageValue extends StorageValue>> { + + public ListStorageValue(List> list) { + super(list); + } + + public ListStorageValue(StorageValue> ...list) { + super(List.of(list)); + } + + @Override + public String toString() { + String msg = "ListStorageValue(["; + + for (StorageValue> entry : this.value) { + msg += entry.toString() + ", "; + } + + msg.substring(0, msg.length() - 3); // Remove ending ", " + + return msg + "])"; + } +} diff --git a/src/main/java/storage/storage_values/MapStorageValue.java b/src/main/java/storage/storage_values/MapStorageValue.java new file mode 100644 index 0000000..456cb7f --- /dev/null +++ b/src/main/java/storage/storage_values/MapStorageValue.java @@ -0,0 +1,27 @@ +package storage.storage_values; + +import java.util.Map; +import java.util.Map.Entry; + +public class MapStorageValue extends StorageValue>> { + + public MapStorageValue(Map> map) { + super(map); + } + + @Override + public String toString() { + String msg = "MapStorageValue({"; + + for (Entry> entries : this.value.entrySet()) { + msg += entries.getKey(); + msg += ":"; + msg += entries.getValue().toString() + ", "; + } + + msg.substring(0, msg.length() - 3); // Remove ending ", " + + return msg + "})"; + } + +} \ No newline at end of file diff --git a/src/main/java/storage/storage_values/NullStorageValue.java b/src/main/java/storage/storage_values/NullStorageValue.java new file mode 100644 index 0000000..923b415 --- /dev/null +++ b/src/main/java/storage/storage_values/NullStorageValue.java @@ -0,0 +1,14 @@ +package storage.storage_values; + +public class NullStorageValue extends StorageValue { + + public NullStorageValue() { + super(null); + } + + @Override + public String toString() { + return "NullStorageValue()"; + } + +} diff --git a/src/main/java/storage/storage_values/StorageValue.java b/src/main/java/storage/storage_values/StorageValue.java new file mode 100644 index 0000000..24865f0 --- /dev/null +++ b/src/main/java/storage/storage_values/StorageValue.java @@ -0,0 +1,27 @@ +package storage.storage_values; + +public abstract class StorageValue { + protected T value; + + public StorageValue(T value) { + this.value = value; + } + + public T getValue() { + return value; + } + + @Override + public abstract String toString(); + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + + StorageValue> other = (StorageValue>) obj; + if (value == null) return other.value == null; + return value.equals(other.value); + } +} diff --git a/src/main/java/storage/storage_values/StringStorageValue.java b/src/main/java/storage/storage_values/StringStorageValue.java new file mode 100644 index 0000000..9dd5634 --- /dev/null +++ b/src/main/java/storage/storage_values/StringStorageValue.java @@ -0,0 +1,14 @@ +package storage.storage_values; + +public class StringStorageValue extends StorageValue { + + public StringStorageValue(String string) { + super(string); + } + + @Override + public String toString() { + return "StringStorageValue(" + this.value + ")"; + } + +} diff --git a/src/main/java/storage/value_formatters/ValueFormatter.java b/src/main/java/storage/value_formatters/ValueFormatter.java new file mode 100644 index 0000000..575b5cb --- /dev/null +++ b/src/main/java/storage/value_formatters/ValueFormatter.java @@ -0,0 +1,27 @@ +package storage.value_formatters; + +import storage.storage_value_adapters.UnsupportedValueException; +import storage.storage_values.StorageValue; + +/** + * An interface denoting the ability of this object to format and parse {@code StorageValues} into objects for storage + * @param The target object format + */ +public interface ValueFormatter { + + /** + * Formats the provided {@code StorageValue} + * @param value The provided {@code StorageValue} + * @return The formatted {@code StorageValue} + * @throws UnsupportedValueException The {@code StorageValue} provided was not supported by this formatter + */ + public F format(StorageValue> value) throws UnsupportedValueException; + + /** + * Parses a given value into a {@code StorageValue} representation + * @param formattedData An object containing data to be parsed + * @return The object parsed into a {@code StorageValue} + * @throws UnsupportedValueException The object provided was not supported by this formatter + */ + public StorageValue> parse(F formattedData) throws UnsupportedValueException; +} diff --git a/src/main/java/storage/value_formatters/ValueToStringFormatter.java b/src/main/java/storage/value_formatters/ValueToStringFormatter.java new file mode 100644 index 0000000..0102e75 --- /dev/null +++ b/src/main/java/storage/value_formatters/ValueToStringFormatter.java @@ -0,0 +1,161 @@ +package storage.value_formatters; + +import java.util.*; +import java.util.Map.Entry; + +import storage.storage_value_adapters.UnsupportedValueException; +import storage.storage_values.*; + +/** + * A simple ValueFormatter + * Parses and produces strings in the form { "entry1":value1, ..., "entryN":value } + */ +public class ValueToStringFormatter implements ValueFormatter { + + protected static final String INDENT = " "; + protected static final String ANY_WHITESPACE = "[\n\t ]*"; + + @Override + public String format(StorageValue> value) throws UnsupportedValueException { + if (value instanceof NullStorageValue) return "null"; + if (value instanceof ListStorageValue) return formatValue((ListStorageValue)value); + if (value instanceof MapStorageValue) return formatValue((MapStorageValue)value); + if (value instanceof StringStorageValue) return formatValue((StringStorageValue)value); + if (value instanceof IntegerStorageValue) return formatValue((IntegerStorageValue)value); + + //TODO: Add more value types and ensure types are differentiable from their stored formats + throw new UnsupportedValueException(value); + } + + /** + * Produces a StorageValue representation of the provided data. + * Note: Errors will not be thrown for incorrect values, ensure the input data is correctly formed. + * @param formattedData The formatted data to be parsed. + * @return The StorageValue representation of the input data. + */ + @Override + public StorageValue> parse(String formattedData) throws UnsupportedValueException { + if (formattedData.startsWith("null")) return new NullStorageValue(); + if (formattedData.startsWith("[")) return parseListFormat(formattedData); + if (formattedData.startsWith("{")) return parseMapFormat(formattedData); + if (formattedData.startsWith("\"")) return parseStringFormat(formattedData); + if (formattedData.matches("[0-9]+.*")) return parseIntegerFormat(formattedData); + + //TODO: Add more value types + throw new UnsupportedValueException(); + } + + + private String formatValue(StringStorageValue value) { + return "\"" + + value.getValue().replace("\"", "\\\"").replace("\\", "\\\\") + + "\""; + } + + private StringStorageValue parseStringFormat(String formattedData) { + if (!formattedData.endsWith("\"")) throw new RuntimeException("The string " + formattedData + " must end with \""); + + formattedData = formattedData.substring(1, formattedData.length() - 1); + formattedData = formattedData.replace("\\\\", "\\"); + + return new StringStorageValue(formattedData); + } + + private String formatValue(IntegerStorageValue value) { + return String.valueOf(value.getValue()); + } + + private IntegerStorageValue parseIntegerFormat(String formattedData) { + return new IntegerStorageValue(Integer.parseInt(formattedData)); + } + + private String formatValue(ListStorageValue value) { + String out = ""; + List> entries = value.getValue(); + + if (entries.isEmpty()) return "[]"; + + for (StorageValue> entry : entries) { + out += format(entry) + ",\n"; + } + + out = out.substring(0, out.length() - 2); //Remove trailing ",\n" + + return "[\n" + indent(out) + "\n]"; + } + + private ListStorageValue parseListFormat(String formattedData) { + formattedData = formattedData.substring(1, formattedData.length() - 1).trim(); + List> list = new ArrayList<>(); + int i = 0; + + while (i < formattedData.length()) { + int endOfValue = findNextElementBoundary(formattedData, i); + list.add(parse(formattedData.substring(i, endOfValue).trim())); + i = endOfValue + 1; // Skip the comma + } + + return new ListStorageValue(list); + } + + private String formatValue(MapStorageValue value) { + String out = ""; + Set>> mapEntries = value.getValue().entrySet(); + + if (mapEntries.isEmpty()) return "{}"; + + for (Entry> entry : mapEntries) { + out += "\"" + entry.getKey() + "\":" + format(entry.getValue()) + ",\n"; + } + + out = out.substring(0, out.length() - 2); //Remove trailing ",\n" + + return "{\n" + indent(out) + "\n}"; + } + + private MapStorageValue parseMapFormat(String formattedData) { + if (!formattedData.endsWith("}")) throw new RuntimeException("The map " + formattedData + " must end with }"); + if (formattedData.matches("\\{" + ANY_WHITESPACE + "\\}")) return new MapStorageValue(Map.of()); + + formattedData = formattedData.substring(1, formattedData.length() - 1).trim(); + Map> map = new HashMap<>(); + int i = 0; + + while (i < formattedData.length()) { + int colonIndex = formattedData.indexOf(':', i); + String key = formattedData.substring(i, colonIndex).trim().replace("\"", ""); + + int startOfValue = colonIndex + 1; + int endOfValue = findNextElementBoundary(formattedData, startOfValue); + + map.put(key, parse(formattedData.substring(startOfValue, endOfValue).trim())); + i = endOfValue + 1; // Skip the comma + } + + return new MapStorageValue(map); + } + + private int findNextElementBoundary(String formattedData, int start) { + int depth = 0; + boolean inQuotes = false; + + for (int i = start; i < formattedData.length(); i++) { + char c = formattedData.charAt(i); + + if (c == '"' && (i == 0 || formattedData.charAt(i - 1) != '\\')) inQuotes = !inQuotes; + if (inQuotes) continue; + + if (c == '{' || c == '[') depth++; + else if (c == '}' || c == ']') depth--; + else if (c == ',' && depth == 0) return i; + } + + return formattedData.length(); + } + + private String indent(String string) { + return INDENT + string.replace("\n", "\n" + INDENT); + } + + protected record ValueFormat(String startDelimiter, String internalRegex, String endDelimiter) {} +} diff --git a/src/main/java/syntax_analysis/SyntaxAnalyser.java b/src/main/java/syntax_analysis/SyntaxAnalyser.java index 6903cb5..406603f 100644 --- a/src/main/java/syntax_analysis/SyntaxAnalyser.java +++ b/src/main/java/syntax_analysis/SyntaxAnalyser.java @@ -1,47 +1,10 @@ package syntax_analysis; -import java.util.*; - import grammar_objects.*; -import helper_objects.LexElementFinder; import syntax_analysis.parsing.*; -public abstract class SyntaxAnalyser { - - protected final Set tokens; - protected final Set nonTerminals; - protected final NonTerminal sentinel; - protected final Set productionRules; - - protected Map> productionsForNonTerminal; - - public SyntaxAnalyser(Set tokens, Set nonTerminals, Set productionRules, NonTerminal sentinel) { - this.tokens = tokens; - this.nonTerminals = nonTerminals; - this.productionRules = productionRules; - this.sentinel = sentinel; - } - - public SyntaxAnalyser(Token[] tokens, NonTerminal[] nonTerminals, ProductionRule[] productionRules, NonTerminal sentinel) { - this.tokens = Set.of(tokens); - this.nonTerminals = Set.of(nonTerminals); - this.productionRules = Set.of(productionRules); - this.sentinel = sentinel; - } - - public SyntaxAnalyser(Set productionRules, NonTerminal sentinel) { - this.tokens = LexElementFinder.tokens(productionRules); - this.nonTerminals = LexElementFinder.nonTerminals(productionRules); - this.productionRules = productionRules; - this.sentinel = sentinel; - } - - public SyntaxAnalyser(ProductionRule[] productionRules, NonTerminal sentinel) { - this.tokens = LexElementFinder.tokens(productionRules); - this.nonTerminals = LexElementFinder.nonTerminals(productionRules); - this.productionRules = Set.of(productionRules); - this.sentinel = sentinel; - } +public interface SyntaxAnalyser { public abstract ParseState analyse(Token[] inputTokens) throws ParseFailedException; + } \ No newline at end of file diff --git a/src/main/java/syntax_analysis/CLR1Parser.java b/src/main/java/syntax_analysis/parsing/parsers/CLR1Parser.java similarity index 99% rename from src/main/java/syntax_analysis/CLR1Parser.java rename to src/main/java/syntax_analysis/parsing/parsers/CLR1Parser.java index a77454a..571cfa5 100644 --- a/src/main/java/syntax_analysis/CLR1Parser.java +++ b/src/main/java/syntax_analysis/parsing/parsers/CLR1Parser.java @@ -1,4 +1,4 @@ -package syntax_analysis; +package syntax_analysis.parsing.parsers; import java.util.*; diff --git a/src/main/java/syntax_analysis/LR0Parser.java b/src/main/java/syntax_analysis/parsing/parsers/LR0Parser.java similarity index 99% rename from src/main/java/syntax_analysis/LR0Parser.java rename to src/main/java/syntax_analysis/parsing/parsers/LR0Parser.java index c733c66..ecac4d1 100644 --- a/src/main/java/syntax_analysis/LR0Parser.java +++ b/src/main/java/syntax_analysis/parsing/parsers/LR0Parser.java @@ -1,4 +1,4 @@ -package syntax_analysis; +package syntax_analysis.parsing.parsers; import java.util.*; @@ -6,7 +6,7 @@ import syntax_analysis.grammar_structure_creation.*; import syntax_analysis.parsing.*; -public class LR0Parser extends SyntaxAnalyser { +public class LR0Parser extends Parser { protected Map> productionMap; protected Set states; diff --git a/src/main/java/syntax_analysis/parsing/parsers/Parser.java b/src/main/java/syntax_analysis/parsing/parsers/Parser.java new file mode 100644 index 0000000..a546c5e --- /dev/null +++ b/src/main/java/syntax_analysis/parsing/parsers/Parser.java @@ -0,0 +1,48 @@ +package syntax_analysis.parsing.parsers; + +import java.util.*; + +import grammar_objects.*; +import helper_objects.LexElementFinder; +import syntax_analysis.SyntaxAnalyser; +import syntax_analysis.parsing.*; + +public abstract class Parser implements SyntaxAnalyser { + + protected final Set tokens; + protected final Set nonTerminals; + protected final NonTerminal sentinel; + protected final Set productionRules; + + protected Map> productionsForNonTerminal; + + public Parser(Set tokens, Set nonTerminals, Set productionRules, NonTerminal sentinel) { + this.tokens = tokens; + this.nonTerminals = nonTerminals; + this.productionRules = productionRules; + this.sentinel = sentinel; + } + + public Parser(Token[] tokens, NonTerminal[] nonTerminals, ProductionRule[] productionRules, NonTerminal sentinel) { + this.tokens = Set.of(tokens); + this.nonTerminals = Set.of(nonTerminals); + this.productionRules = Set.of(productionRules); + this.sentinel = sentinel; + } + + public Parser(Set productionRules, NonTerminal sentinel) { + this.tokens = LexElementFinder.tokens(productionRules); + this.nonTerminals = LexElementFinder.nonTerminals(productionRules); + this.productionRules = productionRules; + this.sentinel = sentinel; + } + + public Parser(ProductionRule[] productionRules, NonTerminal sentinel) { + this.tokens = LexElementFinder.tokens(productionRules); + this.nonTerminals = LexElementFinder.nonTerminals(productionRules); + this.productionRules = Set.of(productionRules); + this.sentinel = sentinel; + } + + public abstract ParseState analyse(Token[] inputTokens) throws ParseFailedException; +} \ No newline at end of file diff --git a/src/main/java/syntax_analysis/SLR1Parser.java b/src/main/java/syntax_analysis/parsing/parsers/SLR1Parser.java similarity index 99% rename from src/main/java/syntax_analysis/SLR1Parser.java rename to src/main/java/syntax_analysis/parsing/parsers/SLR1Parser.java index cdc1cac..91f92f1 100644 --- a/src/main/java/syntax_analysis/SLR1Parser.java +++ b/src/main/java/syntax_analysis/parsing/parsers/SLR1Parser.java @@ -1,4 +1,4 @@ -package syntax_analysis; +package syntax_analysis.parsing.parsers; import java.util.*; diff --git a/src/test/java/code_generation/BasicCodeGeneratorTests.java b/src/test/java/code_generation/BasicCodeGeneratorTests.java index f487b47..1722b28 100644 --- a/src/test/java/code_generation/BasicCodeGeneratorTests.java +++ b/src/test/java/code_generation/BasicCodeGeneratorTests.java @@ -1,4 +1,5 @@ package code_generation; + import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; @@ -7,8 +8,7 @@ import grammar_objects.RuleConvertor; import syntax_analysis.parsing.ParseState; import test_aids.*; -import test_aids.test_grammars.BasicIdentifierTestGrammar; -import test_aids.test_grammars.SmallTestGrammar; +import test_aids.test_grammars.*; public class BasicCodeGeneratorTests { diff --git a/src/test/java/component_construction/CompilerTests.java b/src/test/java/component_construction/CompilerTests.java index 8f3f7c7..14f3f1f 100644 --- a/src/test/java/component_construction/CompilerTests.java +++ b/src/test/java/component_construction/CompilerTests.java @@ -1,9 +1,9 @@ package component_construction; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; -import component_construction.builders.CompilerBuilder; +import component_construction.builders.CustomCompilerBuilder; import component_construction.factories.code_generation.BasicCodeGenFactory; import component_construction.factories.lexical_analysis.GeneralLexicalAnalyserFactory; import component_construction.factories.syntax_analysis.CLR1ParserFactory; @@ -18,7 +18,7 @@ public class CompilerTests { @Test public void basicIdentifierCompiler() throws ParseFailedException { - CompilerBuilder builder = new CompilerBuilder(); + CustomCompilerBuilder builder = new CustomCompilerBuilder(); builder.setComponents( new GeneralLexicalAnalyserFactory(), diff --git a/src/test/java/component_construction/builders/CompilerBuilderTests.java b/src/test/java/component_construction/builders/CompilerBuilderTests.java index f5c0bb7..bae9028 100644 --- a/src/test/java/component_construction/builders/CompilerBuilderTests.java +++ b/src/test/java/component_construction/builders/CompilerBuilderTests.java @@ -1,6 +1,6 @@ package component_construction.builders; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import component_construction.ParameterError; @@ -15,7 +15,7 @@ public class CompilerBuilderTests { @Test public void basicCompilerBuilder() { - CompilerBuilder builder = new CompilerBuilder(); + CustomCompilerBuilder builder = new CustomCompilerBuilder(); builder.setComponents( new GeneralLexicalAnalyserFactory(), new CLR1ParserFactory(), @@ -32,16 +32,16 @@ public void basicCompilerBuilder() { ); - builder.createCompiler(); + assertDoesNotThrow(() -> builder.createCompiler()); } @Test public void nullComponentInputs() { - CompilerBuilder builder1 = new CompilerBuilder(); - CompilerBuilder builder2 = new CompilerBuilder(); - CompilerBuilder builder3 = new CompilerBuilder(); - CompilerBuilder builder4 = new CompilerBuilder(); - CompilerBuilder builder5 = new CompilerBuilder(); + CustomCompilerBuilder builder1 = new CustomCompilerBuilder(); + CustomCompilerBuilder builder2 = new CustomCompilerBuilder(); + CustomCompilerBuilder builder3 = new CustomCompilerBuilder(); + CustomCompilerBuilder builder4 = new CustomCompilerBuilder(); + CustomCompilerBuilder builder5 = new CustomCompilerBuilder(); builder1.setComponents( null, @@ -124,7 +124,7 @@ public void nullComponentInputs() { @Test public void nullLexicalInputs() { - CompilerBuilder builder = new CompilerBuilder(); + CustomCompilerBuilder builder = new CustomCompilerBuilder(); builder.setComponents( new GeneralLexicalAnalyserFactory(), new CLR1ParserFactory(), @@ -138,6 +138,6 @@ public void nullLexicalInputs() { ); - builder.createCompiler(); + assertDoesNotThrow(() -> builder.createCompiler()); } } diff --git a/src/test/java/component_construction/storable/CompilerStorageTests.java b/src/test/java/component_construction/storable/CompilerStorageTests.java new file mode 100644 index 0000000..7b58a0d --- /dev/null +++ b/src/test/java/component_construction/storable/CompilerStorageTests.java @@ -0,0 +1,1061 @@ +package component_construction.storable; + +import static org.junit.jupiter.api.Assertions.*; +import java.io.*; +import java.nio.file.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import storage.exceptions.*; +import storage.value_formatters.*; +import test_aids.exceptions.ExampleException; +import test_aids.storage_entities.custom_components.*; +import test_aids.storage_entities.custom_components.loadable.LoadableTestStorableCustomCompiler; +import test_aids.test_extensions.test_files.*; +import test_aids.test_storage.*; + +@ExtendWith(UseTestFileExtension.class) +public class CompilerStorageTests { + + @Test + public void setTargetPath() { + Path expectedPath = Path.of("./testPath"); + CompilerStorage storage = new CompilerStorage(); + + + storage.setTargetPath(expectedPath); + Path actualPath = storage.getTargetFilepath(); + + + assertEquals(expectedPath, actualPath); + } + + @Test + public void setAbsoluteTargetPath() { + Path expectedPath = Path.of("testPath"); + CompilerStorage storage = new CompilerStorage(); + + + storage.setAbsoluteTargetPath(expectedPath.toString()); + Path actualPath = storage.getTargetFilepath(); + + + assertEquals(expectedPath, actualPath); + } + + @Test + public void setRelativeTargetPath() { + String fileName = "testPath.txt"; + CompilerStorage storage = new CompilerStorage(); + + + storage.setRelativeTargetPath(fileName); + Path actualPath = storage.getTargetFilepath(); + + + Path expectedPath = Path.of("./" + fileName); + assertEquals(expectedPath, actualPath); + } + + @Test + @UseTestFile + public void storeNull(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + assertThrows(NullStorageObjectException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void store(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new TestStringValueFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + + storage.store(compiler); + String actualString = Files.readString(testFile); + + + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void store_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void store_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void store_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void load(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String testString = formatter.format(expectedCompiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + Files.writeString(testFile, testString); + + + StorableCustomCompiler actualCompiler = storage.load(); + + + assertEquals(expectedCompiler, actualCompiler); + } + + @Test + @UseTestFile + public void load_IncorrectFormatter(Path testFile) throws IOException { + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.load()); + } + + @Test + @UseTestFile + public void load_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + Files.writeString(testFile, testString); + + + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void load_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + Files.writeString(testFile, testString); + + + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + void convertAndStoreNull(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + ValueFormatter formatter = new TestStringValueFormatter(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + assertThrows(NullStorageObjectException.class, () -> { + try (outputStream) { + storage.convertAndStore(compiler, formatter, outputStream); + } + }); + } + + @Test + @UseTestFile + void convertAndStoreString(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new TestStringValueFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + storage.convertAndStore(compiler, formatter, outputStream); + } + + + String actualString = Files.readString(testFile); + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void convertAndStoreString_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new TestIntegerValueFormatter(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + try (outputStream) { + assertThrows(StorageFormatMismatchException.class, () -> storage.convertAndStore(compiler, formatter, outputStream)); + } + } + + @Test + @UseTestFile + public void convertAndStoreString_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new TestStringValueFormatter(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + try (outputStream) { + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.convertAndStore(compiler, formatter, outputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void convertAndStoreString_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new TestStringErrorValueFormatter(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + try (outputStream) { + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.convertAndStore(compiler, formatter, outputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + void convertAndLoadStringInto(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(expectedCompiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(formatter) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + storage.convertAndLoadInto(actualCompiler, inputStream); + } + + + assertEquals(expectedCompiler, actualCompiler); + } + + @Test + @UseTestFile + public void convertAndLoadStringInto_IncorrectFormatter(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestIntegerValueFormatter()) + .setFileEditor(new TestStringStreamEditor()); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + assertThrows(StorageFormatMismatchException.class, () -> storage.convertAndLoadInto(actualCompiler, inputStream)); + } + } + + @Test + @UseTestFile + public void convertAndLoadStringInto_FileWriteError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualComipler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestStringValueFormatter()) + .setFileEditor(new TestStringErrorStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.convertAndLoadInto(actualComipler, inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void convertAndLoadStringInto_FormatterError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestStringErrorValueFormatter()) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.convertAndLoadInto(actualCompiler, inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + void convertThenFormatAndLoadStringInto(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(expectedCompiler.getStorageRepresentation()); + + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + storage.convertAndLoadInto(actualCompiler, formatter, inputStream); + } + + assertEquals(expectedCompiler, actualCompiler); + } + + @Test + @UseTestFile + public void convertThenFormatAndLoadStringInto_IncorrectFormatter(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + ValueFormatter> formatter = new TestIntegerValueFormatter(); + + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + assertThrows(StorageFormatMismatchException.class, () -> storage.convertAndLoadInto(actualCompiler, formatter, inputStream)); + } + } + + @Test + @UseTestFile + public void convertThenFormatAndLoadStringInto_FileWriteError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + ValueFormatter> formatter = new TestStringValueFormatter(); + + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.convertAndLoadInto(actualCompiler, formatter, inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void convertThenFormatAndLoadStringInto_FormatterError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + ValueFormatter> formatter = new TestStringErrorValueFormatter(); + + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.convertAndLoadInto(actualCompiler, formatter, inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void storeNullToStream(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + assertThrows(NullStorageObjectException.class, () -> { + try (outputStream) { + storage.store(compiler, outputStream); + } + }); + } + + @Test + @UseTestFile + public void storeToStream(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + storage.store(compiler, outputStream); + } + + + String actualString = Files.readString(testFile); + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void storeToStream_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + assertThrows(StorageFormatMismatchException.class, () -> storage.store(compiler, outputStream)); + } + } + + @Test + @UseTestFile + public void storeToStream_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(compiler, outputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void storeToStream_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(compiler, outputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void loadFromInputStream(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(expectedCompiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + Files.writeString(testFile, expectedString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + StorableCustomCompiler actualcompiler = storage.load(inputStream); + + + assertEquals(expectedCompiler, actualcompiler); + } + + @Test + @UseTestFile + public void loadFromInputStream_IncorrectFormatter(Path testFile) throws IOException { + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + assertThrows(StorageFormatMismatchException.class, () -> storage.load(inputStream)); + } + } + + @Test + @UseTestFile + public void loadFromInputStream_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + Files.writeString(testFile, testString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.load(inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void loadFromInputStream_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + Files.writeString(testFile, testString); + + InputStream inputStream = new FileInputStream(testFile.toFile()); + + + try (inputStream) { + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.load(inputStream) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + } + + @Test + @UseTestFile + public void storeStorableOfNull(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + assertThrows(NullStorageObjectException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void storeStorableOfString(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + + storage.store(compiler); + String actualString = Files.readString(testFile); + + + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void storeStorableOfString_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void storeStorableOfString_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storeStorableOfString_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storeStorableOfNullAtFilepath(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + CompilerStorage storage = new CompilerStorage() + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + assertThrows(NullStorageObjectException.class, () -> storage.store(compiler, testFile.toString())); + } + + @Test + @UseTestFile + public void storeStorableOfStringAtFilepath(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + + storage.store(compiler, testFile.toString()); + String actualString = Files.readString(testFile); + + + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void storeStorableOfStringAtFilepath_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.store(compiler, testFile.toString())); + } + + @Test + @UseTestFile + public void storeStorableOfStringAtFilepath_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(compiler, testFile.toString()) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storeStorableOfStringAtFilepath_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(compiler, testFile.toString()) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storecompilerOfNull(Path testFile) throws IOException { + StorableCustomCompiler compiler = null; + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + assertThrows(NullStorageObjectException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void storecompilerOfString(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(compiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + + storage.store(compiler); + String actualString = Files.readString(testFile); + + + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void storecompilerOfString_IncorrectFormatter(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.store(compiler)); + } + + @Test + @UseTestFile + public void storecompilerOfString_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storecompilerOfString_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler compiler = new TestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(compiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + void LoadStringInto(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(expectedCompiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(formatter) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + + storage.loadInto(actualCompiler); + + + assertEquals(expectedCompiler, actualCompiler); + } + + @Test + @UseTestFile + public void LoadStringInto_IncorrectFormatter(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestStringValueFormatter()) + .setFileEditor(new TestIntegerStreamEditor()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.loadInto(actualCompiler)); + } + + @Test + @UseTestFile + public void LoadStringInto_FileWriteError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestStringValueFormatter()) + .setFileEditor(new TestStringErrorStreamEditor()); + + Files.writeString(testFile, expectedString); + + + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.loadInto(actualCompiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void LoadStringInto_FormatterError(Path testFile) throws IOException { + LoadableTestStorableCustomCompiler expectedCompiler = new LoadableTestStorableCustomCompiler(); + LoadableTestStorableCustomCompiler actualCompiler = new LoadableTestStorableCustomCompiler(); + String expectedString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFormatter(new TestStringErrorValueFormatter()) + .setFileEditor(new TestStringStreamEditor()); + + Files.writeString(testFile, expectedString); + + + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.loadInto(actualCompiler) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void loadFromTargetPath(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + ValueFormatter formatter = new ValueToStringFormatter(); + String expectedString = formatter.format(expectedCompiler.getStorageRepresentation()); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(formatter); + + Files.writeString(testFile, expectedString); + + + StorableCustomCompiler actualcompiler = storage.load(); + + + assertEquals(expectedCompiler, actualcompiler); + } + + @Test + @UseTestFile + public void loadFromTargetPath_IncorrectFormatter(Path testFile) throws IOException { + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.load()); + } + + @Test + @UseTestFile + public void loadFromTargetPath_FileWriteError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + Files.writeString(testFile, testString); + + + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void loadFromTargetPath_FormatterError(Path testFile) throws IOException { + StorableCustomCompiler expectedCompiler = new TestStorableCustomCompiler(); + String testString = expectedCompiler.getStorageRepresentation().toString(); + CompilerStorage storage = new CompilerStorage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + Files.writeString(testFile, testString); + + + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + +} diff --git a/src/test/java/component_construction/storable/StorableCustomCompilerTests.java b/src/test/java/component_construction/storable/StorableCustomCompilerTests.java new file mode 100644 index 0000000..12664a6 --- /dev/null +++ b/src/test/java/component_construction/storable/StorableCustomCompilerTests.java @@ -0,0 +1,5 @@ +package component_construction.storable; + +public class StorableCustomCompilerTests { + // TODO +} diff --git a/src/test/java/component_construction/storable/builders/StorableCustomCompilerBuilderTests.java b/src/test/java/component_construction/storable/builders/StorableCustomCompilerBuilderTests.java new file mode 100644 index 0000000..90e3e70 --- /dev/null +++ b/src/test/java/component_construction/storable/builders/StorableCustomCompilerBuilderTests.java @@ -0,0 +1,217 @@ +package component_construction.storable.builders; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import component_construction.ParameterError; +import component_construction.storable.exceptions.NonStorableComponentException; +import grammars.basic_identifier.BasicIdentifierGrammar; +import grammars.basic_identifier.convertors.XToYToXSemantic; +import lexical_analysis.DynamicTokenRegex; +import test_aids.storage_entities.custom_components.factories.*; + +public class StorableCustomCompilerBuilderTests { + + @Test + public void getSelf() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + + + assertEquals(builder, builder.getThis()); + } + + @Test + public void basicCompilerBuilder() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + builder.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") //TODO: Using [0-9]+(\\.[0-9]+)? for all tests would be better + } + ); + + + assertDoesNotThrow(() -> builder.createCompiler()); + } + + @Test + public void nullComponentInputs() { + StorableCustomCompilerBuilder builder1 = new StorableCustomCompilerBuilder(); + StorableCustomCompilerBuilder builder2 = new StorableCustomCompilerBuilder(); + StorableCustomCompilerBuilder builder3 = new StorableCustomCompilerBuilder(); + StorableCustomCompilerBuilder builder4 = new StorableCustomCompilerBuilder(); + StorableCustomCompilerBuilder builder5 = new StorableCustomCompilerBuilder(); + + builder1.setComponents( + null, + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + builder2.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + null, + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + builder3.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + null, + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + builder4.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + null, + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + builder5.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + null, + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + + + assertThrows(ParameterError.class, () -> builder1.createCompiler()); + assertThrows(ParameterError.class, () -> builder2.createCompiler()); + assertThrows(ParameterError.class, () -> builder3.createCompiler()); + assertThrows(ParameterError.class, () -> builder4.createCompiler()); + assertThrows(ParameterError.class, () -> builder5.createCompiler()); + } + + @Test + public void nullLexicalInputs() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + builder.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + null, + null, + null, + null + ); + + + assertDoesNotThrow(() -> builder.createCompiler()); + } + + @Test + public void setcomponents_nonStorableLexicalAnalyser() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + builder.setComponents( + new TestCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + + + assertThrows(NonStorableComponentException.class, () -> builder.createCompiler()); + } + + @Test + public void setcomponents_nonStorableSyntaxAnalyser() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + builder.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestCustomSyntaxAnalyserFactory(), + new TestStorableCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + + + assertThrows(NonStorableComponentException.class, () -> builder.createCompiler()); + } + + @Test + public void setcomponents_nonStorableCodeGenerator() { + StorableCustomCompilerBuilder builder = new StorableCustomCompilerBuilder(); + builder.setComponents( + new TestStorableCustomLexicalAnalyserFactory(), + new TestStorableCustomSyntaxAnalyserFactory(), + new TestCustomCodeGeneratorFactory(), + BasicIdentifierGrammar.produce(), + XToYToXSemantic.produce(), + new String[] {" "}, + new String[] {"+", "=", ";"}, + new String[] {}, + new DynamicTokenRegex[] { + new DynamicTokenRegex("[A-Za-z]+", "identifier"), + new DynamicTokenRegex("[0-9]+(\\.[0-9]+)?", "number") + } + ); + + + assertThrows(NonStorableComponentException.class, () -> builder.createCompiler()); + } + +} diff --git a/src/test/java/component_construction/storable/dynamic_loading/LoadableByTests.java b/src/test/java/component_construction/storable/dynamic_loading/LoadableByTests.java new file mode 100644 index 0000000..07b9de8 --- /dev/null +++ b/src/test/java/component_construction/storable/dynamic_loading/LoadableByTests.java @@ -0,0 +1,63 @@ +package component_construction.storable.dynamic_loading; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import component_construction.storable.exceptions.IncorrectlyFormattedException; +import test_aids.storage_entities.loadableby_entities.*; + +public class LoadableByTests { + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader() { + Class>> loadableBy = (Class>>)(Class>)LoadableObject.class; + Class> actualLoader = LoadableBy.getTargetLoader(loadableBy); + + assertEquals(StandardLoader.class, actualLoader); + } + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader_genericLoader() { + Class>> loadableBy = (Class>>)(Class>)GenericallyLoadableObject.class; + + assertThrows(IncorrectlyFormattedException.class, () -> LoadableBy.getTargetLoader(loadableBy)); + } + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader_wildcardLoader() { + Class>> loadableBy = (Class>>)(Class>)WildcardLoadableObject.class; + + assertThrows(IncorrectlyFormattedException.class, () -> LoadableBy.getTargetLoader(loadableBy)); + } + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader_additionalInterface() { + Class>> loadableBy = (Class>>)(Class>)TestLoadableObject.class; + Class> actualLoader = LoadableBy.getTargetLoader(loadableBy); + + assertEquals(StandardLoader.class, actualLoader); + } + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader_additionalGenericInterface() { + Class>>> loadableBy = (Class>>>)(Class>)GenericTestLoadableObject.class; + Class>> actualLoader = LoadableBy.getTargetLoader(loadableBy); + + assertEquals(StandardLoader.class, actualLoader); + } + + @Test + @SuppressWarnings("unchecked") + public void getTargetLoader_additionalConcretisedGenericInterface() { + Class>>> loadableBy = (Class>>>)(Class>)ConcretisedGenericTestLoadableObject.class; + Class>> actualLoader = LoadableBy.getTargetLoader(loadableBy); + + assertEquals(StandardLoader.class, actualLoader); + } + +} diff --git a/src/test/java/component_construction/storable/dynamic_loading/LoaderTests.java b/src/test/java/component_construction/storable/dynamic_loading/LoaderTests.java new file mode 100644 index 0000000..fca3c0e --- /dev/null +++ b/src/test/java/component_construction/storable/dynamic_loading/LoaderTests.java @@ -0,0 +1,27 @@ +package component_construction.storable.dynamic_loading; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import component_construction.storable.exceptions.MissingEmptyConstructorException; +import test_aids.storage_entities.*; + +public class LoaderTests { + + @Test + @SuppressWarnings("unchecked") + public void construct() { + Class> loaderClass = (Class>)(Class>)TestObjectLoader.class; + + assertDoesNotThrow(() -> Loader.construct(loaderClass)); + } + + @Test + @SuppressWarnings("unchecked") + public void construct_IncorrectlyFormedLoader() { + Class> loaderClass = (Class>)(Class>)IncorrectlyFormedLoader.class; + + assertThrows(MissingEmptyConstructorException.class, () -> Loader.construct(loaderClass)); + } + +} diff --git a/src/test/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructorTests.java b/src/test/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructorTests.java new file mode 100644 index 0000000..d0c7ad8 --- /dev/null +++ b/src/test/java/component_construction/storable/dynamic_loading/ReflectiveClassConstructorTests.java @@ -0,0 +1,598 @@ +package component_construction.storable.dynamic_loading; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import test_aids.storage_entities.*; +import test_aids.storage_entities.TestDynamicObject.*; + +public class ReflectiveClassConstructorTests { + + protected String TestDynamicObjectNamespace = TestDynamicObject.class.getPackageName(); + protected String nonExistantTestDynamicObjectPath = TestDynamicObjectNamespace + ".NonExistantTestDynamicObject"; + protected String nonExistantStaticInnerTestDynamicObjectPath = TestDynamicObjectNamespace + ".NonExistantTestDynamicObject$StaticInnerTestDynamicObject"; + protected String nonExistantInnerTestDynamicObjectPath = TestDynamicObjectNamespace + ".NonExistantTestDynamicObject$InnerTestDynamicObject"; + + @Test + public void construct_noParameters_class() throws ClassNotFoundException { + TestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class + ); + TestDynamicObject expectedObject = new TestDynamicObject(); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_noParameters_staticInnerClass() throws ClassNotFoundException { + StaticInnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class + ); + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_noParameters_innerClass() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + + InnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] {parentObject.getClass()}, + new Object[] {parentObject} + ); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_noParameters_nonExistantClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantTestDynamicObjectPath, + TestDynamicObject.class + ) + ); + } + + @Test + public void construct_noParameters_nonExistantStaticInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantStaticInnerTestDynamicObjectPath, + TestDynamicObject.class + ) + ); + } + + @Test + public void construct_noParameters_nonExistantInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantInnerTestDynamicObjectPath, + TestDynamicObject.class + ) + ); + } + + @Test + public void construct_oneParameter_class_intParam() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + + TestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {expectedObject.a} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_staticInnerClass_intParam() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + + StaticInnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {expectedObject.e} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_innerClass_intParam() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + + InnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + int.class + }, + new Object[] { + parentObject, + expectedObject.c + } + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_class_stringParam() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.b = "Test"; + + TestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {String.class}, + new Object[] {expectedObject.b} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_staticInnerClass_stringParam() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.f = "Test"; + + StaticInnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {String.class}, + new Object[] {expectedObject.f} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_innerClass_stringParam() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.d = "Test"; + + InnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + String.class + }, + new Object[] { + parentObject, + expectedObject.d + } + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_oneParameter_class_falseBooleanType() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {boolean.class}, + new Object[] {expectedObject.a} + ) + ); + } + + @Test + public void construct_oneParameter_staticInnerClass_falseBooleanType() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {boolean.class}, + new Object[] {expectedObject.e} + ) + ); + } + + @Test + public void construct_oneParameter_innerClass_falseBooleanType() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + boolean.class + }, + new Object[] { + parentObject, + expectedObject.c + } + ) + ); + } + + @Test + public void construct_oneParameter_class_falseBooleanParam() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {false} + ) + ); + } + + @Test + public void construct_oneParameter_staticInnerClass_falseBooleanParam() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {false} + ) + ); + } + + @Test + public void construct_oneParameter_innerClass_falseBooleanParam() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + int.class + }, + new Object[] { + parentObject, + false + } + ) + ); + } + + @Test + public void construct_oneParameter_nonExistantClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {1} + ) + ); + } + + @Test + public void construct_oneParameter_nonExistantStaticInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantStaticInnerTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {1} + ) + ); + } + + @Test + public void construct_oneParameter_nonExistantInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantInnerTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class}, + new Object[] {1} + ) + ); + } + + @Test + public void construct_manyParameters_class_correctParams() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + expectedObject.b = "Test"; + + TestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {expectedObject.a, expectedObject.b} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_manyParameters_staticInnerClass_correctParams() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + expectedObject.f = "Test"; + + StaticInnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {expectedObject.e, expectedObject.f} + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_manyParameters_innerClass_correctParams() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + expectedObject.d = "Test"; + + InnerTestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + int.class, + String.class + }, + new Object[] { + parentObject, + expectedObject.c, + expectedObject.d + } + ); + + assertEquals(expectedObject, actualObject); + } + + @Test + public void construct_manyParameters_class_falseBooleanType() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + expectedObject.b = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {boolean.class, String.class}, + new Object[] {expectedObject.a, expectedObject.b} + ) + ); + } + + @Test + public void construct_manyParameters_staticInnerClass_falseBooleanType() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + expectedObject.f = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {boolean.class, String.class}, + new Object[] {expectedObject.e, expectedObject.f} + ) + ); + } + + @Test + public void construct_manyParameters_innerClass_falseBooleanType() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + expectedObject.d = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + boolean.class, + String.class + }, + new Object[] { + parentObject, + expectedObject.c, + expectedObject.d + } + ) + ); + } + + @Test + public void construct_manyParameters_class_falseBooleanParam() throws ClassNotFoundException { + TestDynamicObject expectedObject = new TestDynamicObject(); + expectedObject.a = 1; + expectedObject.b = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {false, expectedObject.b} + ) + ); + } + + @Test + public void construct_manyParameters_staticInnerClass_falseBooleanParam() throws ClassNotFoundException { + StaticInnerTestDynamicObject expectedObject = new StaticInnerTestDynamicObject(); + expectedObject.e = 1; + expectedObject.f = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + StaticInnerTestDynamicObject.class.getName(), + StaticInnerTestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {false, expectedObject.f} + ) + ); + } + + @Test + public void construct_manyParameters_innerClass_falseBooleanParam() throws ClassNotFoundException { + TestDynamicObject parentObject = new TestDynamicObject(); + InnerTestDynamicObject expectedObject = parentObject.new InnerTestDynamicObject(); + expectedObject.c = 1; + expectedObject.d = "Test"; + + assertThrows(IllegalArgumentException.class, () -> + new ReflectiveClassConstructor() + .construct( + InnerTestDynamicObject.class.getName(), + InnerTestDynamicObject.class, + new Class>[] { + parentObject.getClass(), + int.class, + String.class + }, + new Object[] { + parentObject, + false, + expectedObject.d + } + ) + ); + } + + @Test + public void construct_manyParameters_nonExistantClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {1, "Test"} + ) + ); + } + + @Test + public void construct_manyParameters_nonExistantStaticInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantStaticInnerTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {1, "Test"} + ) + ); + } + + @Test + public void construct_manyParameters_nonExistantInnerClass() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> + new ReflectiveClassConstructor() + .construct( + nonExistantInnerTestDynamicObjectPath, + TestDynamicObject.class, + new Class>[] {int.class, String.class}, + new Object[] {1, "Test"} + ) + ); + } + + @Test + public void construct_subclassAsTargetType() throws ClassNotFoundException { + TestDynamicObjectSubclass expectedObject = new TestDynamicObjectSubclass( + 1, + "Test", + true + ); + + TestDynamicObject actualObject = new ReflectiveClassConstructor() + .construct( + TestDynamicObjectSubclass.class.getName(), + TestDynamicObject.class, + new Class>[] { int.class, String.class, boolean.class }, + new Object[] { expectedObject.a, expectedObject.b, expectedObject.c } + ); + + assertEquals((TestDynamicObject)expectedObject, actualObject); + } + + @Test + public void construct_superclassAsTargetType() throws ClassNotFoundException { + assertThrows(ClassCastException.class, () -> + new ReflectiveClassConstructor() + .construct( + TestDynamicObject.class.getName(), + TestDynamicObjectSubclass.class, + new Class>[] { int.class, String.class }, + new Object[] { 1, "Test" } + ) + ); + } +} diff --git a/src/test/java/component_construction/storable/factories/StorableCustomCompilerFactoryTests.java b/src/test/java/component_construction/storable/factories/StorableCustomCompilerFactoryTests.java new file mode 100644 index 0000000..8368ab5 --- /dev/null +++ b/src/test/java/component_construction/storable/factories/StorableCustomCompilerFactoryTests.java @@ -0,0 +1,464 @@ +package component_construction.storable.factories; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.junit.jupiter.api.Test; + +import code_generation.CodeGenerator; +import component_construction.storable.exceptions.*; +import lexical_analysis.LexicalAnalyser; +import storage.storage_values.*; +import syntax_analysis.SyntaxAnalyser; +import test_aids.storage_entities.custom_components.*; +import test_aids.storage_entities.custom_components.loadable.LoadableStorableCustomLexicalAnalyser; +import test_aids.storage_entities.custom_components.loadableBy.LoadableByStorableCustomLexicalAnalyser; + +public class StorableCustomCompilerFactoryTests { + + protected record TypedComponent(String name, ListStorageValue description, Factory factory) {} + + protected static final TypedComponent lexicalComponent = new TypedComponent<>( + "TestLexicalAnalyser", + new ListStorageValue( + new StringStorageValue("TestLexicalAnalyser") + ), + (description) -> { + assertEquals( + new ListStorageValue( + new StringStorageValue("TestLexicalAnalyser") + ), + description + ); + + return new TestStorableCustomLexicalAnalyser(); + } + ); + + protected static final TypedComponent syntaxComponent = new TypedComponent<>( + "TestSyntaxAnalyser", + new ListStorageValue( + new StringStorageValue("TestSyntaxAnalyser") + ), + (description) -> { + assertEquals( + new ListStorageValue( + new StringStorageValue("TestSyntaxAnalyser") + ), + description + ); + + return new TestStorableCustomSyntaxAnalyser(); + } + ); + + protected static final TypedComponent codeGeneratorComponent = new TypedComponent<>( + "TestCodeGenerator", + new ListStorageValue( + new StringStorageValue("TestCodeGenerator") + ), + (description) -> { + assertEquals( + new ListStorageValue( + new StringStorageValue("TestCodeGenerator") + ), + description + ); + + return new TestStorableCustomCodeGenerator(); + } + ); + + @Test + public void produce() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addLexicalAnalyserFactory( + lexicalComponent.name(), + lexicalComponent.factory() + ) + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertDoesNotThrow(() -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(lexicalComponent.name()), + lexicalComponent.description() + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_existingNamedClassComponents() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addLexicalAnalyserFactory( + "TestCustomLexicalAnalyser", + lexicalComponent.factory() + ) + .addSyntaxAnalyserFactory( + "TestCustomSyntaxAnalyser", + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + "TestCustomCodeGenerator", + codeGeneratorComponent.factory() + ); + + assertDoesNotThrow(() -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue("TestCustomLexicalAnalyser"), + lexicalComponent.description() + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue("TestCustomSyntaxAnalyser"), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue("TestCustomCodeGenerator"), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_LoadableByLexicalAnalyser() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(LoadableByStorableCustomLexicalAnalyser.class.getName()), + lexicalComponent.description() + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + ); + } + + @Test + public void produce_LoadableLexicalAnalyser() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(LoadableStorableCustomLexicalAnalyser.class.getName()), + lexicalComponent.description() + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + ); + } + + @Test + public void produce_ConstructableLexicalAnalyser() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(ConstructableStorableLexicalAnalyser.class.getName()), + new ListStorageValue(List.of()) + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + ); + } + + @Test + public void produce_incorrectFormat_noMap() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(IncorrectLoadValueFormat.class, () -> factory.produce( + new ListStorageValue(List.of( + new ListStorageValue( + new StringStorageValue("lexicalAnalyser"), + new ListStorageValue( + new StringStorageValue(lexicalComponent.name()), + new ListStorageValue(List.of()) + ) + ), + new ListStorageValue( + new StringStorageValue("syntaxAnalyser"), + new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ) + ), + new ListStorageValue( + new StringStorageValue("codeGenerator"), + new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + ) + )) + )); + } + + @Test + public void produce_incorrectFormat_missingKey() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addLexicalAnalyserFactory( + lexicalComponent.name(), + lexicalComponent.factory() + ) + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(MissingKeyException.class, () -> factory.produce( + new MapStorageValue(Map.of( + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_incorrectFormat_multipleMissingKeys() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addLexicalAnalyserFactory( + lexicalComponent.name(), + lexicalComponent.factory() + ) + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(MissingKeyException.class, () -> factory.produce( + new MapStorageValue(Map.of( + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ) + )) + )); + } + + @Test + public void produce_incorrectFormat_emptyMap() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addLexicalAnalyserFactory( + lexicalComponent.name(), + lexicalComponent.factory() + ) + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(MissingKeyException.class, () -> factory.produce( + new MapStorageValue(Map.of()) + )); + } + + @Test + public void produce_incorrectFormat_nonListComponentDescription() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(IncorrectLoadValueFormat.class, () -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new MapStorageValue(Map.of( + lexicalComponent.name(), + lexicalComponent.description() + )), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_nonExistentComponentClass() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(NonExistentComponentException.class, () -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue("NonExistantClass"), + new ListStorageValue(List.of()) + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_nonComponentClass() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(ComponentCastException.class, () -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(TestCustomFalseLexicalAnalyser.class.getName()), + new ListStorageValue(List.of()) + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } + + @Test + public void produce_componentMissingCorrectConstructor() { + StorableCustomCompilerFactory factory = new StorableCustomCompilerFactory() + .addSyntaxAnalyserFactory( + syntaxComponent.name(), + syntaxComponent.factory() + ) + .addCodeGeneratorFactory( + codeGeneratorComponent.name(), + codeGeneratorComponent.factory() + ); + + assertThrows(ReflectiveLoadFailure.class, () -> factory.produce( + new MapStorageValue(Map.of( + "lexicalAnalyser", new ListStorageValue( + new StringStorageValue(NonConstructableLexicalAnalyser.class.getName()), + new ListStorageValue(List.of()) + ), + "syntaxAnalyser", new ListStorageValue( + new StringStorageValue(syntaxComponent.name()), + syntaxComponent.description() + ), + "codeGenerator", new ListStorageValue( + new StringStorageValue(codeGeneratorComponent.name()), + codeGeneratorComponent.description() + ) + )) + )); + } +} diff --git a/src/test/java/storage/StorageTests.java b/src/test/java/storage/StorageTests.java new file mode 100644 index 0000000..00c9b1c --- /dev/null +++ b/src/test/java/storage/StorageTests.java @@ -0,0 +1,1465 @@ +package storage; + +import static org.junit.jupiter.api.Assertions.*; +import java.io.*; +import java.nio.file.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.*; + +import storage.exceptions.*; +import storage.external_interfaces.Storable; +import storage.storage_values.*; +import storage.value_formatters.*; +import test_aids.exceptions.ExampleException; +import test_aids.test_extensions.test_files.*; +import test_aids.test_storage.*; + +@ExtendWith(UseTestFileExtension.class) +public class StorageTests { + + @Test + public void setTargetPath() { + Path expectedPath = Path.of("./testPath"); + Storage storage = new Storage(); + + + storage.setTargetPath(expectedPath); + Path actualPath = storage.getTargetFilepath(); + + + assertEquals(expectedPath, actualPath); + } + + @Test + public void setAbsoluteTargetPath() { + Path expectedPath = Path.of("testPath"); + Storage storage = new Storage(); + + + storage.setAbsoluteTargetPath(expectedPath.toString()); + Path actualPath = storage.getTargetFilepath(); + + + assertEquals(expectedPath, actualPath); + } + + @Test + public void setRelativeTargetPath() { + String fileName = "testPath.txt"; + Storage storage = new Storage(); + + + storage.setRelativeTargetPath(fileName); + Path actualPath = storage.getTargetFilepath(); + + + Path expectedPath = Path.of("./" + fileName); + assertEquals(expectedPath, actualPath); + } + + @Test + @UseTestFile + public void storeNull(Path testFile) throws IOException { + StorageValue> storageValue = null; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + assertThrows(NullStorageObjectException.class, () -> storage.store(storageValue)); + } + + @Test + @UseTestFile + public void storeString(Path testFile) throws IOException { + String expectedString = "testString"; + StorageValue> storageValue = new TestStorageValue(expectedString); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + storage.store(storageValue); + String actualString = Files.readString(testFile); + + + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + public void storeInteger(Path testFile) throws IOException { + int expectedInt = 10; + StorageValue> storageValue = new TestStorageValue(expectedInt); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + storage.store(storageValue); + int actualString = Integer.parseInt(Files.readString(testFile)); + + + assertEquals(expectedInt, actualString); + } + + @Test + @UseTestFile + public void storeString_IncorrectFormatter(Path testFile) throws IOException { + String expectedString = "testString"; + StorageValue> storageValue = new TestStorageValue(expectedString); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.store(storageValue)); + } + + @Test + @UseTestFile + public void storeString_FileWriteError(Path testFile) throws IOException { + String expectedString = "testString"; + StorageValue> storageValue = new TestStorageValue(expectedString); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + + StoreFailureException exception = assertThrows( + StoreFailureException.class, + () -> storage.store(storageValue) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void storeString_FormatterError(Path testFile) throws IOException { + String expectedString = "testString"; + StorageValue> storageValue = new TestStorageValue(expectedString); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + + FormattingException exception = assertThrows( + FormattingException.class, + () -> storage.store(storageValue) + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void loadString(Path testFile) throws IOException { + String testString = "testString"; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + Files.writeString(testFile, testString); + + + StorageValue> actualStorageValue = storage.load(); + + + StorageValue> expectedStorageValue = new TestStorageValue(testString); + assertEquals(expectedStorageValue, actualStorageValue); + } + + @Test + @UseTestFile + public void loadInteger(Path testFile) throws IOException { + int testInteger = 10; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestIntegerStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + Files.writeString(testFile, Integer.toString(testInteger)); + + + StorageValue> actualStorageValue = storage.load(); + + + StorageValue> expectedStorageValue = new TestStorageValue(testInteger); + assertEquals(expectedStorageValue, actualStorageValue); + } + + @Test + @UseTestFile + public void loadEmptyString(Path testFile) throws IOException { + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + StorageValue> actualStorageValue = storage.load(); + + + StorageValue> expectedStorageValue = new TestStorageValue(""); + assertEquals(expectedStorageValue, actualStorageValue); + } + + @Test + @UseTestFile + public void loadEmptyInteger(Path testFile) throws IOException { + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestIntegerStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.load() + ); + assertInstanceOf(NumberFormatException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void loadString_IncorrectFormatter(Path testFile) throws IOException { + String testString = "testString"; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestIntegerValueFormatter()); + + Files.writeString(testFile, testString); + + + assertThrows(StorageFormatMismatchException.class, () -> storage.load()); + } + + @Test + @UseTestFile + public void loadString_FileWriteError(Path testFile) throws IOException { + String testString = "testString"; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringErrorStreamEditor()) + .setFormatter(new TestStringValueFormatter()); + + Files.writeString(testFile, testString); + + + LoadFailureException exception = assertThrows( + LoadFailureException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + public void loadString_FormatterError(Path testFile) throws IOException { + String testString = "testString"; + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()) + .setFormatter(new TestStringErrorValueFormatter()); + + Files.writeString(testFile, testString); + + + FormatParseException exception = assertThrows( + FormatParseException.class, + () -> storage.load() + ); + assertInstanceOf(ExampleException.class, exception.getCause()); + } + + @Test + @UseTestFile + void convertAndStoreNull(Path testFile) throws IOException { + Storable storable = null; + ValueFormatter formatter = new TestStringValueFormatter(); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + assertThrows(NullStorageObjectException.class, () -> { + try (outputStream) { + storage.convertAndStore(storable, formatter, outputStream); + } + }); + } + + @Test + @UseTestFile + void convertAndStoreString(Path testFile) throws IOException { + String expectedString = "testString"; + + Storable storable = new TestStorable(expectedString); + ValueFormatter formatter = new TestStringValueFormatter(); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestStringStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + storage.convertAndStore(storable, formatter, outputStream); + } + + + String actualString = Files.readString(testFile); + assertEquals(expectedString, actualString); + } + + @Test + @UseTestFile + void convertAndStoreInteger(Path testFile) throws IOException { + int expectedInteger = 10; + + Storable storable = new TestStorable(expectedInteger); + ValueFormatter formatter = new TestIntegerValueFormatter(); + Storage storage = new Storage() + .setTargetPath(testFile) + .setFileEditor(new TestIntegerStreamEditor()); + + OutputStream outputStream = new FileOutputStream(testFile.toFile()); + + + try (outputStream) { + storage.convertAndStore(storable, formatter, outputStream); + } + + + int actualInteger = Integer.parseInt(Files.readString(testFile)); + assertEquals(expectedInteger, actualInteger); + } + + @Test + @UseTestFile + public void convertAndStoreString_IncorrectFormatter(Path testFile) throws IOException { + String expectedString = "testString"; + + Storable storable = new TestStorable(expectedString); + ValueFormatter