From ff3fec5e2e1638a4304e5b3e4db1b9b82fd5823c Mon Sep 17 00:00:00 2001 From: Pavel Marek Date: Mon, 22 Sep 2025 15:43:13 +0200 Subject: [PATCH 1/2] Bump Google java format version to 1.28.0 --- project/plugins.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/plugins.sbt b/project/plugins.sbt index 07cbb14059e5..97faae45b091 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -7,7 +7,7 @@ addSbtPlugin("com.simplytyped" % "sbt-antlr4" % "0.8.3") libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.2" libraryDependencies += "commons-io" % "commons-io" % "2.12.0" libraryDependencies += "nl.gn0s1s" %% "bump" % "0.1.3" -libraryDependencies += "com.google.googlejavaformat" % "google-java-format" % "1.18.1" +libraryDependencies += "com.google.googlejavaformat" % "google-java-format" % "1.28.0" libraryDependencies += "com.softwaremill.retry" %% "retry" % "0.3.6" scalacOptions ++= Seq("-deprecation", "-feature") From ad8a19185d7a8d8a77f5106e70b4efaff65a3941 Mon Sep 17 00:00:00 2001 From: Pavel Marek Date: Mon, 22 Sep 2025 15:48:47 +0200 Subject: [PATCH 2/2] fmt --- .../java/org/enso/common/HostEnsoUtils.java | 16 +- .../src/main/java/org/enso/runner/Main.java | 15 +- .../src/main/java/org/enso/runner/Repl.java | 9 +- .../test/java/org/enso/runner/UtilsTest.java | 21 +- .../compiler/benchmarks/CodeGenerator.java | 6 +- .../ImportStandardLibrariesBenchmark.java | 2 +- .../module/ManyErrorsBenchmark.java | 6 +- .../module/ManyNestedBlocksBenchmark.java | 2 +- .../semantic/CallableBenchmarks.java | 8 +- .../benchmarks/semantic/EqualsBenchmarks.java | 73 +- .../benchmarks/semantic/ListBenchmarks.java | 118 +- .../NamedDefaultedArgumentBenchmarks.java | 4 +- .../NestedPatternCompilationBenchmarks.java | 32 +- .../semantic/RecursionBenchmarks.java | 14 +- .../semantic/WarningBenchmarks.java | 26 +- .../enso/compiler/dump/igv/EnsoModuleAST.java | 14 +- .../org/enso/compiler/dump/igv/Utils.java | 5 +- .../common/BuildScopeFromModuleAlgorithm.java | 34 +- .../org/enso/compiler/docs/BindingSorter.java | 71 +- .../analyse/AmbiguousImportsAnalysis.java | 148 +- .../pass/analyse/ImportSymbolAnalysis.java | 38 +- .../enso/compiler/pass/analyse/TailCall.java | 44 +- .../analyse/types/TypeCheckAlgorithm.java | 15 +- .../pass/analyse/types/TypeCompatibility.java | 8 +- .../types/TypeInferenceSignatures.java | 6 +- .../pass/analyse/types/TypePropagation.java | 20 +- .../pass/analyse/types/TypeResolver.java | 30 +- .../pass/desugar/SectionsToBinOp.java | 36 +- .../pass/lint/ShadowedPatternFields.java | 5 +- .../lint/unusedimports/UnusedImports.java | 2 +- .../pass/resolve/MethodDefinitions.java | 14 +- .../compiler/phase/ImportResolverForIR.java | 300 ++-- .../exports/ConflictingResolutionsError.java | 10 +- .../UsedSymbolsCollectorTest.java | 186 +-- .../enso/compiler/test/BindingsMapTest.java | 8 +- .../enso/compiler/test/CompilerErrorTest.java | 11 +- .../compiler/test/MultipleProjectsTest.java | 8 +- .../compiler/test/SyntheticModulesTest.java | 7 +- .../enso/compiler/test/UnusedImportsTest.java | 232 +-- .../common/test/ContextInsightSetupTest.java | 13 +- .../dump/test/ApiModificationTest.java | 42 +- .../test/AnnotationsCompilerTest.java | 62 +- .../test/BindingsMapResolutionTest.java | 188 +-- .../enso/compiler/test/ErrorCompilerTest.java | 300 ++-- .../enso/compiler/test/ExecCompilerTest.java | 281 ++-- .../compiler/test/ExecStrictCompilerTest.java | 20 +- .../test/ExportCycleDetectionTest.java | 54 +- .../compiler/test/ExportedSymbolsTest.java | 89 +- .../enso/compiler/test/IfThenElseTest.java | 121 +- .../test/ImportsAndFQNConsistencyTest.java | 9 +- .../enso/compiler/test/TypeInferenceTest.java | 1069 ++++++------- .../test/TypesFromSignaturesTest.java | 78 +- .../compiler/test/WarningsAsErrorsTest.java | 20 +- .../passes/resolve/NameResolutionTest.java | 130 +- .../caches/HelloWorldCacheTest.java | 6 +- .../caches/IRCacheLocationTest.java | 12 +- .../interpreter/caches/ModuleCacheTest.java | 20 +- .../interpreter/node/ProgramRootNodeTest.java | 3 +- .../meta/TypeOfNodeMultiValueTest.java | 8 +- .../builtin/meta/TypeOfNodeTest.java | 8 +- .../runtime/ManagedResourceTest.java | 16 +- .../enso/interpreter/runtime/ModuleTest.java | 22 +- .../org/enso/interpreter/runtime/RefTest.java | 6 +- .../runtime/progress/ProgressTest.java | 76 +- .../interpreter/test/AnyOrStaticTest.java | 22 +- .../org/enso/interpreter/test/AnyToTest.java | 28 +- .../interpreter/test/AtomConstructorTest.java | 6 +- .../test/AutoscopedConstructorTest.java | 42 +- .../enso/interpreter/test/BigNumberTest.java | 77 +- .../interpreter/test/BinaryOpFloatTest.java | 24 +- .../interpreter/test/BinaryOpIntegerTest.java | 24 +- .../org/enso/interpreter/test/CaseOfTest.java | 12 +- .../test/ConversionMethodTests.java | 170 +-- .../interpreter/test/DebuggingEnsoTest.java | 346 ++--- .../test/DiagnosticFormatterTest.java | 3 +- .../interpreter/test/EnsoMultiValueTest.java | 188 +-- .../test/EqualsConversionsTest.java | 48 +- .../test/EqualsMultiValueTest.java | 104 +- .../org/enso/interpreter/test/EqualsTest.java | 8 +- .../test/ExtensionMethodResolutionTest.java | 21 +- .../test/FindExceptionMessageTest.java | 92 +- .../test/InterpreterSymbolResolutionTest.java | 34 +- .../interpreter/test/LazyAtomFieldTest.java | 170 +-- .../org/enso/interpreter/test/ListTest.java | 24 +- .../test/MethodResolutionTest.java | 34 +- .../test/NativeLibraryFinderTest.java | 6 +- .../interpreter/test/PolyglotErrorTest.java | 100 +- .../PolyglotFindExceptionMessageTest.java | 8 +- .../org/enso/interpreter/test/PrintTest.java | 167 +- .../enso/interpreter/test/RootNamesTest.java | 12 +- .../interpreter/test/SharedEngineTest.java | 14 +- .../test/SignaturePolyglotTest.java | 16 +- .../enso/interpreter/test/SignatureTest.java | 532 +++---- .../interpreter/test/StdLibLoggingTest.java | 8 +- .../enso/interpreter/test/StdLibLogsTest.java | 16 +- .../test/TypeInferenceConsistencyTest.java | 93 +- .../interpreter/test/ValuesGenerator.java | 281 ++-- .../interpreter/test/VectorBuilderTest.java | 18 +- .../enso/interpreter/test/VectorSortTest.java | 8 +- .../org/enso/interpreter/test/VectorTest.java | 90 +- .../enso/interpreter/test/WarningsTest.java | 40 +- .../test/asserts/AssertionsTest.java | 46 +- .../test/asserts/DisabledAssertionsTest.java | 2 +- .../SuccessfulAssertionExpressionTest.java | 2 +- .../InvokeBuiltinMethodViaInteropTest.java | 3 +- .../test/exports/ExportConstructorTest.java | 32 +- .../exports/ExportConversionMethodTest.java | 55 +- .../exports/ExportExtensionMethodTest.java | 80 +- .../test/exports/ExportModuleTest.java | 20 +- .../exports/ExportResolutionOrderingTest.java | 33 +- .../test/exports/ExportStaticMethodTest.java | 61 +- .../interpreter/test/hash/HashCodeTest.java | 6 +- .../test/imports/ImportSymbolsTest.java | 45 +- .../AvoidIdInstrumentationTagTest.java | 32 +- .../test/instrument/FunctionPointerTest.java | 3 +- .../instrument/IncrementalUpdatesTest.java | 20 +- .../test/instrument/InsightForEnsoTest.java | 24 +- .../test/instrument/RuntimeProgressTest.java | 46 +- .../test/instrument/RuntimeServerTesting.java | 24 +- .../WarningInstrumentationTest.java | 18 +- .../test/interop/AtomInteropTest.java | 222 +-- .../test/interop/JavaInteropTest.java | 112 +- .../test/interop/JsInteropTest.java | 18 +- .../test/interop/MetaObjectTest.java | 23 +- .../test/interop/MetaServicesTest.java | 38 +- .../test/interop/TypeMembersTest.java | 78 +- .../test/meta/EnsoProjectTest.java | 42 +- .../interpreter/test/meta/MetaIsATest.java | 8 +- .../test/meta/MetaTypeMethodsTest.java | 20 +- .../PrivateCheckDisabledTest.java | 3 +- .../PrivateConstructorAccessTest.java | 11 +- .../PrivateMethodAccessTest.java | 24 +- .../test/scope/ModuleScopeTest.java | 48 +- .../DataflowErrorPropagationTest.java | 22 +- .../test/semantic/FunctionIdentityTest.java | 6 +- .../interpreter/arrow/node/ArrowEvalNode.java | 13 +- .../enso/interpreter/epb/ForeignEvalNode.java | 17 +- .../enso/interpreter/epb/PyForeignNode.java | 60 +- .../interpreter/epb/ForeignEvalNodeTest.java | 11 +- .../processor/test/TestIRProcessorInline.java | 574 +++---- .../processor/IRNodeClassGenerator.java | 26 +- .../methodgen/BuilderMethodGenerator.java | 18 +- .../methodgen/ChildrenMethodGenerator.java | 12 +- .../methodgen/DuplicateMethodGenerator.java | 106 +- .../MapExpressionsMethodGenerator.java | 62 +- .../methodgen/ToStringMethodGenerator.java | 12 +- .../java/org/enso/compiler/core/TreeToIr.java | 840 ++++++----- .../core/EnsoParserMultiThreadedTest.java | 6 +- .../enso/compiler/core/EnsoParserTest.java | 1340 +++++++++-------- .../tck/EnsoTckLanguageProvider.java | 48 +- .../builtin/meta/EqualsBuiltinNode.java | 18 +- .../builtin/number/integer/IntegerNode.java | 24 +- .../number/integer/ParseIntegerNode.java | 6 +- .../node/typecheck/SingleTypeCheckNode.java | 42 +- .../enso/interpreter/runtime/EnsoContext.java | 8 +- .../interpreter/runtime/EnsoPolyglotJava.java | 5 +- .../runtime/data/hash/HashMapRemoveNode.java | 3 +- .../runtime/data/hash/HashMapToTextNode.java | 3 +- .../interpreter/runtime/data/text/Text.java | 58 +- .../runtime/scope/TopLevelScope.java | 44 +- .../dsl/builtins/MethodGenerator.java | 7 +- .../dsl/builtins/TypeWithKind.java | 8 +- .../dsl/impl/BuiltinsProcessor.java | 18 +- .../enso/jvm/interop/impl/OtherJvmObject.java | 6 +- .../environment/chdir/WorkingDirectory.java | 5 +- .../persist/impl/PersistableProcessor.java | 56 +- .../java/org/enso/persist/Persistable.java | 7 +- .../java/org/enso/persist/Persistance.java | 18 +- .../java/org/enso/persist/package-info.java | 8 +- .../org/enso/test/utils/ProjectUtils.java | 5 +- .../ydoc/polyfill/ParserPolyfillTest.java | 12 +- .../org/enso/ydoc/polyfill/web/ZlibTest.java | 148 +- .../benchmarks/processor/SpecCollector.java | 172 +-- .../org/enso/version/VersionDescription.java | 28 +- .../base/enso_cloud/SecretValueResolver.java | 15 +- .../org/enso/base/numeric/Decimal_Utils.java | 2 +- .../base/parser/NumberWithSeparators.java | 42 +- .../enso/base/polyglot/NumericConverter.java | 14 +- .../base/time/EnsoDateTimeFormatterImpl.java | 16 +- .../java/org/enso/database/JDBCProxy.java | 9 +- .../fetchers/ColumnFetcherFactory.java | 89 +- .../org/enso/google/CredentialsHelper.java | 7 +- .../google/GoogleCredentialsProvider.java | 6 +- .../enso/microsoft/azure/AzureCredential.java | 9 +- .../microsoft/azure/CredentialHelper.java | 19 +- .../SnowflakeColumnFetcherFactory.java | 50 +- .../org/enso/table/aggregations/Mean.java | 8 +- .../java/org/enso/table/aggregations/Sum.java | 22 +- .../table/data/column/DataQualityMetrics.java | 35 +- .../table/data/column/builder/Builder.java | 13 +- .../operation/BinaryCoalescingOperation.java | 10 +- .../data/column/operation/IsInOperation.java | 123 +- .../data/column/operation/JsonOperation.java | 12 +- .../operation/NumericColumnAdapter.java | 42 +- .../operation/UnaryOperationNumeric.java | 8 +- .../column/operation/cast/CastOperation.java | 28 +- .../operation/comparators/Comparators.java | 30 +- .../column/operation/masks/MaskOperation.java | 32 +- .../column/operation/unary/NotOperation.java | 23 +- .../operation/unary/RoundOperation.java | 78 +- .../operation/unary/UnaryRoundOperation.java | 5 +- .../data/column/storage/type/StorageType.java | 15 +- .../org/enso/table/data/table/Column.java | 5 +- .../data/table/join/lookup/LookupJoin.java | 8 +- .../enso/table/excel/ExcelConnectionPool.java | 4 +- .../org/enso/table/excel/ExcelHeaders.java | 4 +- .../java/org/enso/table/excel/ExcelRow.java | 4 +- .../java/org/enso/table/excel/ExcelUtils.java | 16 +- .../org/enso/table/write/ExcelWriter.java | 13 +- .../java/org/enso/tableau/HyperFormat.java | 56 +- .../enso/shttp/cloud_mock/CloudAuthRenew.java | 4 +- 211 files changed, 6865 insertions(+), 6235 deletions(-) diff --git a/engine/common/src/main/java/org/enso/common/HostEnsoUtils.java b/engine/common/src/main/java/org/enso/common/HostEnsoUtils.java index 16f6bb9302ee..484b795b6f84 100644 --- a/engine/common/src/main/java/org/enso/common/HostEnsoUtils.java +++ b/engine/common/src/main/java/org/enso/common/HostEnsoUtils.java @@ -4,8 +4,7 @@ import org.graalvm.polyglot.PolyglotException; public final class HostEnsoUtils { - private HostEnsoUtils() { - } + private HostEnsoUtils() {} /** * Extracts a string representation for a polyglot exception. @@ -14,12 +13,13 @@ private HostEnsoUtils() { * @return message representing the exception */ public static String findExceptionMessage(Throwable ex) { - return ex.getMessage() != null ? ex.getMessage() : switch (ex) { - case PolyglotException exception when exception.isHostException() -> - exception.asHostException().getClass().getName(); - default -> - ex.getClass().getName(); - }; + return ex.getMessage() != null + ? ex.getMessage() + : switch (ex) { + case PolyglotException exception when exception.isHostException() -> + exception.asHostException().getClass().getName(); + default -> ex.getClass().getName(); + }; } /** diff --git a/engine/runner/src/main/java/org/enso/runner/Main.java b/engine/runner/src/main/java/org/enso/runner/Main.java index efb761e96d48..809d7ec09033 100644 --- a/engine/runner/src/main/java/org/enso/runner/Main.java +++ b/engine/runner/src/main/java/org/enso/runner/Main.java @@ -1018,11 +1018,11 @@ private void runRepl( var mainMethodName = "internal_repl_entry_point___"; var dummySourceToTriggerRepl = """ - from Standard.Base import all - import Standard.Base.Runtime.Debug + from Standard.Base import all + import Standard.Base.Runtime.Debug - $mainMethodName = Debug.breakpoint - """ + $mainMethodName = Debug.breakpoint + """ .replace("$mainMethodName", mainMethodName); var replModuleName = "Internal_Repl_Module___"; var projectRoot = projectPath != null ? projectPath : ""; @@ -1267,7 +1267,7 @@ private boolean shouldEnableIrCaches(CommandLine line) { if (line.hasOption(ENABLE_STATIC_ANALYSIS_OPTION)) { if (line.hasOption(IR_CACHES_OPTION)) { throw exitFail( - "" + "" + ENABLE_STATIC_ANALYSIS_OPTION + " requires IR caches to be disabled, so --" + IR_CACHES_OPTION @@ -1602,8 +1602,9 @@ private void launch(String[] args) throws IOException, InterruptedException, URI launchJvm(originalCwdOrNull, line, props, component, javaExecutable); return; } else { - throw exitFail("Cannot find java executable to run in JVM mode. JVM mode " + - "was enforced either by `--jvm` option or by project configuration."); + throw exitFail( + "Cannot find java executable to run in JVM mode. JVM mode " + + "was enforced either by `--jvm` option or by project configuration."); } } } diff --git a/engine/runner/src/main/java/org/enso/runner/Repl.java b/engine/runner/src/main/java/org/enso/runner/Repl.java index 840ee9e73ccd..1b70696febe2 100644 --- a/engine/runner/src/main/java/org/enso/runner/Repl.java +++ b/engine/runner/src/main/java/org/enso/runner/Repl.java @@ -23,10 +23,11 @@ final class Repl implements SessionManager { switch (content) { case ":list", ":l" -> { var bindings = executor.listBindings(); - bindings.foreachEntry((name, value) -> { - replIO.println(name + " = " + value); - return null; - }); + bindings.foreachEntry( + (name, value) -> { + replIO.println(name + " = " + value); + return null; + }); } case ":quit", "q" -> { continueRunning = false; diff --git a/engine/runner/src/test/java/org/enso/runner/UtilsTest.java b/engine/runner/src/test/java/org/enso/runner/UtilsTest.java index f1bcef90385b..87abb8060480 100644 --- a/engine/runner/src/test/java/org/enso/runner/UtilsTest.java +++ b/engine/runner/src/test/java/org/enso/runner/UtilsTest.java @@ -25,14 +25,14 @@ public void printStackTrace1() throws Exception { var f = folder.newFile("p.enso"); var code = """ - from Standard.Base import all + from Standard.Base import all - a = b - b = c - c = Panic.throw "foo" + a = b + b = c + c = Panic.throw "foo" - main = a - """; + main = a + """; Files.writeString(f.toPath(), code); var lines = new ArrayList(); @@ -55,10 +55,11 @@ public void printStackTrace1() throws Exception { assertEquals( """ - Execution finished with an error: foo - at throw(Internal) - at c(Internal) - at main(Internal)""", + Execution finished with an error: foo + at throw(Internal) + at c(Internal) + at main(Internal)\ + """, lines.stream().collect(Collectors.joining("\n"))); } diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/CodeGenerator.java b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/CodeGenerator.java index 5e6b86b1742f..c35556103d74 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/CodeGenerator.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/CodeGenerator.java @@ -162,7 +162,7 @@ public String createExpression(List identifiers, int size) { return switch (size) { case 0 -> nextLiteral(); - // Either a single identifier or a method call on the identifier + // Either a single identifier or a method call on the identifier case 1 -> { var sb = new StringBuilder(); var ident = chooseIdentifier(identifiers); @@ -174,7 +174,7 @@ public String createExpression(List identifiers, int size) { } yield sb.toString(); } - // Method call or binary operator + // Method call or binary operator case 2 -> { var sb = new StringBuilder(); var shouldCallMethod = random.nextBoolean(); @@ -196,7 +196,7 @@ public String createExpression(List identifiers, int size) { } yield sb.toString(); } - // Split into two expressions with random size + // Split into two expressions with random size default -> { var sb = new StringBuilder(); var shouldCallMethod = random.nextBoolean(); diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ImportStandardLibrariesBenchmark.java b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ImportStandardLibrariesBenchmark.java index 5111bca2a843..3a7a1d123605 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ImportStandardLibrariesBenchmark.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ImportStandardLibrariesBenchmark.java @@ -66,7 +66,7 @@ public class ImportStandardLibrariesBenchmark { "Connection_Options.Connection_Options"); private static final String IMPORTS = - """ +""" from Standard.Base import all from Standard.Table import all from Standard.Database import all diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyErrorsBenchmark.java b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyErrorsBenchmark.java index c7a678ee854c..5c23a9f77fe6 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyErrorsBenchmark.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyErrorsBenchmark.java @@ -72,12 +72,12 @@ public void setup(BenchmarkParams params) throws IOException { for (int i = 0; i < ERRORS_CNT; i++) { var rndInt = random.nextInt(0, 3); switch (rndInt) { - // Expression with unknown identifiers + // Expression with unknown identifiers case 0 -> { var expr = codeGen.createExpression(UNDEFINED_IDENTIFIERS, EXPR_SIZE); sb.append(" ").append(expr).append(System.lineSeparator()); } - // Inline type ascription with unknown identifier + // Inline type ascription with unknown identifier case 1 -> { var expr = codeGen.createExpression(definedIdentifiers, EXPR_SIZE); sb.append(" ") @@ -85,7 +85,7 @@ public void setup(BenchmarkParams params) throws IOException { .append(expr) .append(System.lineSeparator()); } - // Put arrows before, after, and between expressions + // Put arrows before, after, and between expressions case 2 -> { var expr1 = codeGen.createExpression(definedIdentifiers, EXPR_SIZE); var expr2 = codeGen.createExpression(definedIdentifiers, EXPR_SIZE); diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyNestedBlocksBenchmark.java b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyNestedBlocksBenchmark.java index f196b3a40097..26ca0df54695 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyNestedBlocksBenchmark.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/compiler/benchmarks/module/ManyNestedBlocksBenchmark.java @@ -165,7 +165,7 @@ private void createNestedBlocks(int nestedBlockIdx) { .append(System.lineSeparator()); createNestedBlocks(nestedBlockIdx + 1); } - // Create a nested anonymous function + // Create a nested anonymous function case 3 -> { var argsCnt = random.nextInt(1, ANONYMOUS_FUNC_MAX_ARGS); sb.append(spaces); diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java index 2efc299abc6a..cdeb87376e17 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java @@ -25,7 +25,7 @@ public class CallableBenchmarks { private static final long HUNDRED_MILLION = 100_000_000L; private static final String SUM_TCO_FROM_CALL_CODE = - """ +""" from Standard.Base.Data.Numbers import all type Foo @@ -40,7 +40,7 @@ public class CallableBenchmarks { """; private static final String SUM_TCO_METHOD_CALL_CODE = - """ +""" summator = acc -> current -> if current == 0 then acc else @Tail_Call summator (acc + current) (current - 1) @@ -50,7 +50,7 @@ public class CallableBenchmarks { """; private static final String SUM_TCO_METHOD_CALL_WITH_NAMED_ARGUMENTS_CODE = - """ +""" summator = acc -> current -> if current == 0 then acc else @Tail_Call summator (current = current - 1) (acc = acc + current) @@ -60,7 +60,7 @@ public class CallableBenchmarks { """; private static final String SUM_TCO_METHOD_CALL_WITH_DEFAULTED_ARGUMENTS_CODE = - """ +""" summator = (acc = 0) -> current -> if current == 0 then acc else @Tail_Call summator (current = current - 1) (acc = acc + current) diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/EqualsBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/EqualsBenchmarks.java index 8369ed900ffe..09b53223cd2c 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/EqualsBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/EqualsBenchmarks.java @@ -60,39 +60,39 @@ public void initializeBenchmark(BenchmarkParams params) throws Exception { var codeBuilder = new StringBuilder( """ - import Standard.Base.Data.Range.Extensions - import Standard.Base.Data.Numbers.Number - import Standard.Base.Data.Ordering.Ordering - import Standard.Base.Data.Ordering.Comparable - - type Num - Value n - - Num.from (that:Number) = Num.Value that - Comparable.from (_:Number) = Num_Comparator - Comparable.from (_:Num) = Num_Comparator - - type Num_Comparator - compare x:Num y:Num = Ordering.compare x.n y.n - hash x:Num = Ordering.hash x.n - - type Node - C1 f1 - C2 f1 f2 - C3 f1 f2 f3 - C4 f1 f2 f3 f4 - C5 f1 f2 f3 f4 f5 - Nil - Value value - - eq_vec vec1 vec2 = - (0.up_to vec1.length).map idx-> - v1 = vec1.at idx - v2 = vec2.at idx - v1 == v2 - - eq x y = x == y - """); + import Standard.Base.Data.Range.Extensions + import Standard.Base.Data.Numbers.Number + import Standard.Base.Data.Ordering.Ordering + import Standard.Base.Data.Ordering.Comparable + + type Num + Value n + + Num.from (that:Number) = Num.Value that + Comparable.from (_:Number) = Num_Comparator + Comparable.from (_:Num) = Num_Comparator + + type Num_Comparator + compare x:Num y:Num = Ordering.compare x.n y.n + hash x:Num = Ordering.hash x.n + + type Node + C1 f1 + C2 f1 f2 + C3 f1 f2 f3 + C4 f1 f2 f3 f4 + C5 f1 f2 f3 f4 f5 + Nil + Value value + + eq_vec vec1 vec2 = + (0.up_to vec1.length).map idx-> + v1 = vec1.at idx + v2 = vec2.at idx + v1 == v2 + + eq x y = x == y + """); // Indexes where `True` is expected. Inside the generated vectors, on a predefined indexes, // we put "constant" values, such that when the elements at these indexes are compared, // `True` is returned. @@ -169,7 +169,8 @@ public void initializeBenchmark(BenchmarkParams params) throws Exception { default -> throw new IllegalStateException("Unexpected benchmark: " + params.getBenchmark()); } - codeBuilder.append(""" + codeBuilder.append( + """ bench _ = eq_vec vec1 vec2 """); @@ -418,8 +419,8 @@ public String createSource() { case 3 -> "(Node.C3 "; case 4 -> "(Node.C4 "; case 5 -> "(Node.C5 "; - default -> throw new AssertionError( - "Unexpected number of children: " + children.size()); + default -> + throw new AssertionError("Unexpected number of children: " + children.size()); }; var sb = new StringBuilder(); sb.append(ctor); diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/ListBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/ListBenchmarks.java index da3dfbd6a321..362f5b4d3799 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/ListBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/ListBenchmarks.java @@ -39,84 +39,84 @@ public void initializeBenchmark(BenchmarkParams params) throws Exception { var benchmarkName = SrcUtil.findName(params); var code = """ - from Standard.Base.Any import Any - from Standard.Base.Data.List.List import Cons, Nil - from Standard.Base.Data.Text import Text - from Standard.Base.Data.Numbers import Float - from Standard.Base import Integer - import Standard.Base.IO + from Standard.Base.Any import Any + from Standard.Base.Data.List.List import Cons, Nil + from Standard.Base.Data.Text import Text + from Standard.Base.Data.Numbers import Float + from Standard.Base import Integer + import Standard.Base.IO - type V - Val (a : Integer) + type V + Val (a : Integer) - zero = V.Val 0 + zero = V.Val 0 - plus_v self (other : V) = V.Val self.a+other.a + plus_v self (other : V) = V.Val self.a+other.a - + self other:V -> Integer = self.a+other.a + + self other:V -> Integer = self.a+other.a - sum_int list (acc:V) = - case list of - Nil -> acc.a - Cons x xs -> @Tail_Call V.sum_int xs (acc.plus_v (V.Val x)) + sum_int list (acc:V) = + case list of + Nil -> acc.a + Cons x xs -> @Tail_Call V.sum_int xs (acc.plus_v (V.Val x)) - sum_conv list (acc:V) = - case list of - Nil -> acc.a - Cons x xs -> @Tail_Call V.sum_conv xs (acc.plus_v x) + sum_conv list (acc:V) = + case list of + Nil -> acc.a + Cons x xs -> @Tail_Call V.sum_conv xs (acc.plus_v x) - v_zero = V.zero - v_sum_int = V.sum_int - v_sum_conv = V.sum_conv + v_zero = V.zero + v_sum_int = V.sum_int + v_sum_conv = V.sum_conv - V.from (that : Integer) = V.Val that + V.from (that : Integer) = V.Val that - type Lenivy - Nic - Hlava ~x ~xs + type Lenivy + Nic + Hlava ~x ~xs - map self fn = case self of - Lenivy.Nic -> Lenivy.Nic - Lenivy.Hlava x xs -> Lenivy.Hlava (fn x) (xs.map fn) + map self fn = case self of + Lenivy.Nic -> Lenivy.Nic + Lenivy.Hlava x xs -> Lenivy.Hlava (fn x) (xs.map fn) - plus_one list = list.map (x -> x + 1) + plus_one list = list.map (x -> x + 1) - leniva_suma list acc = case list of - Lenivy.Nic -> acc - Lenivy.Hlava x xs -> @Tail_Call leniva_suma xs acc+x + leniva_suma list acc = case list of + Lenivy.Nic -> acc + Lenivy.Hlava x xs -> @Tail_Call leniva_suma xs acc+x - lenivy_generator n = - go x v l = if x > n then l else - @Tail_Call go x+1 v+1 (Lenivy.Hlava v l) - go 1 1 Lenivy.Nic + lenivy_generator n = + go x v l = if x > n then l else + @Tail_Call go x+1 v+1 (Lenivy.Hlava v l) + go 1 1 Lenivy.Nic - sum list acc = - case list of - Nil -> acc - Cons x xs -> @Tail_Call sum xs acc+x + sum list acc = + case list of + Nil -> acc + Cons x xs -> @Tail_Call sum xs acc+x - sum_any list (acc:Any) = - case list of - Nil -> acc - Cons x xs -> @Tail_Call sum_any xs acc+x + sum_any list (acc:Any) = + case list of + Nil -> acc + Cons x xs -> @Tail_Call sum_any xs acc+x - sum_int list (acc:Integer) = - case list of - Nil -> acc - Cons x xs -> @Tail_Call sum_int xs acc+x + sum_int list (acc:Integer) = + case list of + Nil -> acc + Cons x xs -> @Tail_Call sum_int xs acc+x - sum_multi list (acc:Text|Float|Integer|Any) = - case list of - Nil -> acc - Cons x xs -> @Tail_Call sum_multi xs acc+x + sum_multi list (acc:Text|Float|Integer|Any) = + case list of + Nil -> acc + Cons x xs -> @Tail_Call sum_multi xs acc+x - generator n = - go x v l = if x > n then l else - @Tail_Call go x+1 v+1 (Cons v l) - go 1 1 Nil + generator n = + go x v l = if x > n then l else + @Tail_Call go x+1 v+1 (Cons v l) + go 1 1 Nil - wrap_v s = s.map v-> V.Val v - """; + wrap_v s = s.map v-> V.Val v + """; var module = ctx.eval(SrcUtil.source(benchmarkName, code)); diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java index e0b5e0ef6bbd..91d14cff6ea2 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java @@ -25,7 +25,7 @@ public class NamedDefaultedArgumentBenchmarks { private static long HUNDRED_MILLION = 100_000_000L; private static final String SUM_TCO_WITH_NAMED_ARGUMENTS_CODE = - """ +""" import Standard.Base.Data.Numbers main = sumTo -> summator = acc -> current -> @@ -36,7 +36,7 @@ public class NamedDefaultedArgumentBenchmarks { """; private static final String SUM_TCO_WITH_DEFAULTED_ARGUMENTS_CODE = - """ +""" import Standard.Base.Data.Numbers main = sumTo -> summator = (acc = 0) -> current -> diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NestedPatternCompilationBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NestedPatternCompilationBenchmarks.java index 04241af59226..8070da1f76f4 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NestedPatternCompilationBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/NestedPatternCompilationBenchmarks.java @@ -37,25 +37,25 @@ public void initializeBenchmark(BenchmarkParams params) throws Exception { benchmarkName = SrcUtil.findName(params); code = """ - import Standard.Base.Data.Numbers + import Standard.Base.Data.Numbers - type List - Cons a b - Nil + type List + Cons a b + Nil - test x = - case x of - List.Nil -> 0 - List.Cons a List.Nil -> a - List.Cons a (List.Cons b List.Nil) -> a+b - List.Cons a (List.Cons b (List.Cons c List.Nil)) -> a+b+c - List.Cons a (List.Cons b (List.Cons c (List.Cons d List.Nil))) -> a+b+c+d - List.Cons a (List.Cons b (List.Cons c (List.Cons d (List.Cons e List.Nil)))) -> a+b+c+d+e - List.Cons a (List.Cons b (List.Cons c (List.Cons d (List.Cons e (List.Cons f List.Nil))))) -> a+b+c+d+e+f + test x = + case x of + List.Nil -> 0 + List.Cons a List.Nil -> a + List.Cons a (List.Cons b List.Nil) -> a+b + List.Cons a (List.Cons b (List.Cons c List.Nil)) -> a+b+c + List.Cons a (List.Cons b (List.Cons c (List.Cons d List.Nil))) -> a+b+c+d + List.Cons a (List.Cons b (List.Cons c (List.Cons d (List.Cons e List.Nil)))) -> a+b+c+d+e + List.Cons a (List.Cons b (List.Cons c (List.Cons d (List.Cons e (List.Cons f List.Nil))))) -> a+b+c+d+e+f - list_of_6 = - List.Cons 1 (List.Cons 2 (List.Cons 3 (List.Cons 4 (List.Cons 5 (List.Cons 6 List.Nil))))) - """; + list_of_6 = + List.Cons 1 (List.Cons 2 (List.Cons 3 (List.Cons 4 (List.Cons 5 (List.Cons 6 List.Nil))))) + """; } @Benchmark diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java index dd23f00c323b..b314bcc79007 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java @@ -24,7 +24,7 @@ @State(Scope.Benchmark) public class RecursionBenchmarks { private static final String SUM_TCO_CODE = - """ +""" main = sumTo -> summator = acc -> current -> if current == 0 then acc else @Tail_Call summator acc+current current-1 @@ -34,7 +34,7 @@ public class RecursionBenchmarks { """; private static final String SUM_TCO_FOLD_LIKE_CODE = - """ +""" main = sumTo -> summator = acc -> i -> f -> if i == 0 then acc else @Tail_Call summator (f acc i) (i - 1) f @@ -43,7 +43,7 @@ public class RecursionBenchmarks { """; private static final String SUM_RECURSIVE_CODE = - """ +""" main = sumTo -> summator = i -> if i == 0 then 0 else i + summator (i - 1) res = summator sumTo @@ -51,7 +51,7 @@ public class RecursionBenchmarks { """; private static final String OVERSATURATED_RECURSIVE_CALL_TCO_CODE = - """ +""" main = sumTo -> summator = acc -> i -> f -> if i == 0 then acc else @Tail_Call summator (f acc i) (i - 1) f @@ -60,7 +60,7 @@ public class RecursionBenchmarks { """; private static final String SUM_STATE_TCO_CODE = - """ +""" from Standard.Base.Data.Numbers import Number import Standard.Base.Runtime.State @@ -75,7 +75,7 @@ State.put Number (acc + n) """; private static final String SUM_TCO_WITH_EVAL_CODE = - """ +""" import Standard.Base.Runtime.Debug main = sumTo -> @@ -87,7 +87,7 @@ State.put Number (acc + n) """; private static final String NESTED_THUNK_SUM_CODE = - """ +""" from Standard.Base.Data.Numbers import Number import Standard.Base.Runtime.State import Standard.Base.Nothing.Nothing diff --git a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/WarningBenchmarks.java b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/WarningBenchmarks.java index 4e8336f85e7f..8e853a08b321 100644 --- a/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/WarningBenchmarks.java +++ b/engine/runtime-benchmarks/src/main/java/org/enso/interpreter/bench/benchmarks/semantic/WarningBenchmarks.java @@ -85,24 +85,24 @@ public void initializeBench(BenchmarkParams params) throws IOException { var setupCode = new StringBuilder( """ - from Standard.Base import all + from Standard.Base import all - create_vec size elem = Runtime.no_inline <| - Vector.fill size elem + create_vec size elem = Runtime.no_inline <| + Vector.fill size elem - elem = - 42 + elem = + 42 - elem_const_with_warning = Runtime.no_inline <| - x = 42 - Warning.attach "Foo!" x + elem_const_with_warning = Runtime.no_inline <| + x = 42 + Warning.attach "Foo!" x - elem_with_warning v = Runtime.no_inline <| - Warning.attach "Foo!" v + elem_with_warning v = Runtime.no_inline <| + Warning.attach "Foo!" v - map_vector_with_warnings vec = Runtime.no_inline <| - vec.map (e-> elem_with_warning e) - """); + map_vector_with_warnings vec = Runtime.no_inline <| + vec.map (e-> elem_with_warning e) + """); // generate random vector var randomIntVectorName = "vector_with_random_values"; diff --git a/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/EnsoModuleAST.java b/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/EnsoModuleAST.java index 298bab67aaeb..2d64fdf7df0e 100644 --- a/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/EnsoModuleAST.java +++ b/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/EnsoModuleAST.java @@ -56,11 +56,12 @@ private EnsoModuleAST(IRSource ctx, Map nodeIds) { this.nodeIds = nodeIds; assert ctx != null; this.ctx = ctx; - this.root = switch (ctx.ir()) { - case Module m -> buildTree(m); - case Expression e -> buildTree(e); - case null, default -> throw new IllegalArgumentException("ir: " + ctx.ir()); - }; + this.root = + switch (ctx.ir()) { + case Module m -> buildTree(m); + case Expression e -> buildTree(e); + case null, default -> throw new IllegalArgumentException("ir: " + ctx.ir()); + }; } /** @@ -68,8 +69,7 @@ private EnsoModuleAST(IRSource ctx, Map nodeIds) { * @param moduleName FQN of the module. * @param nodeIds Mapping of IR node UUIDs to sequential IDs expected by the IGV. */ - static EnsoModuleAST create( - IRSource ctx, Map nodeIds) { + static EnsoModuleAST create(IRSource ctx, Map nodeIds) { return new EnsoModuleAST(ctx, nodeIds); } diff --git a/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/Utils.java b/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/Utils.java index 383ddea8dac3..696a19b4b31d 100644 --- a/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/Utils.java +++ b/engine/runtime-compiler-dump-igv/src/main/java/org/enso/compiler/dump/igv/Utils.java @@ -25,9 +25,8 @@ static String label(Object obj) { case Method.Explicit m -> "Method.Explicit ('" + m.methodName().name() + "')"; case Method.Conversion c -> "Method.Conversion ('" + c.methodName().name() + "')"; case Method.Binding b -> "Method.Binding ('" + b.methodName().name() + "')"; - case DefinitionArgument.Specified arg -> "DefinitionArgument.Specified ('" - + arg.name().name() - + "')"; + case DefinitionArgument.Specified arg -> + "DefinitionArgument.Specified ('" + arg.name().name() + "')"; case Expression.Binding b -> "Expression.Binding ('" + b.name().name() + "')"; case Pattern.Name n -> "Pattern.Name ('" + n.name().name() + "')"; case Pattern.Constructor c -> "Pattern.Constructor ('" + c.constructor().name() + "')"; diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/common/BuildScopeFromModuleAlgorithm.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/common/BuildScopeFromModuleAlgorithm.java index 8e30eb45167f..8d199d7202f7 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/common/BuildScopeFromModuleAlgorithm.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/common/BuildScopeFromModuleAlgorithm.java @@ -82,8 +82,8 @@ private void processBindings(Module module) { case Definition.Type typ -> processTypeDefinition(typ); case Method.Explicit method -> processMethodDefinition(method); case Method.Conversion conversion -> processConversion(conversion); - default -> logger.warn( - "Unexpected binding type: {}", binding.getClass().getCanonicalName()); + default -> + logger.warn("Unexpected binding type: {}", binding.getClass().getCanonicalName()); } } } @@ -136,12 +136,13 @@ protected final TypeScopeReferenceType getTypeDefiningMethod(Method.Explicit met } return switch (metadata.target()) { - case BindingsMap.ResolvedType resolvedType -> associatedTypeFromResolvedType( - resolvedType, method.isStatic()); - case BindingsMap.ResolvedModule resolvedModule -> associatedTypeFromResolvedModule( - resolvedModule); - default -> throw new IllegalStateException( - "Unexpected target type: " + metadata.target().getClass().getCanonicalName()); + case BindingsMap.ResolvedType resolvedType -> + associatedTypeFromResolvedType(resolvedType, method.isStatic()); + case BindingsMap.ResolvedModule resolvedModule -> + associatedTypeFromResolvedModule(resolvedModule); + default -> + throw new IllegalStateException( + "Unexpected target type: " + metadata.target().getClass().getCanonicalName()); }; } } @@ -155,14 +156,15 @@ protected final TypeScopeReferenceType getTypeResolution(IR expr) { } return switch (resolution.target()) { - case BindingsMap.ResolvedType resolvedType -> associatedTypeFromResolvedType( - resolvedType, false); - case BindingsMap.ResolvedModule resolvedModule -> associatedTypeFromResolvedModule( - resolvedModule); - default -> throw new IllegalStateException( - "Unexpected target type: " - + resolution.target().getClass().getCanonicalName() - + ", should be caught by MethodDefinitions pass."); + case BindingsMap.ResolvedType resolvedType -> + associatedTypeFromResolvedType(resolvedType, false); + case BindingsMap.ResolvedModule resolvedModule -> + associatedTypeFromResolvedModule(resolvedModule); + default -> + throw new IllegalStateException( + "Unexpected target type: " + + resolution.target().getClass().getCanonicalName() + + ", should be caught by MethodDefinitions pass."); }; } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/docs/BindingSorter.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/docs/BindingSorter.java index 08576461d9a8..3b9cc78fc004 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/docs/BindingSorter.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/docs/BindingSorter.java @@ -3,33 +3,31 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - import org.enso.compiler.core.ir.Module; import org.enso.compiler.core.ir.module.scope.Definition; import org.enso.compiler.core.ir.module.scope.Definition.Data; import org.enso.compiler.core.ir.module.scope.Definition.Type; import org.enso.compiler.core.ir.module.scope.definition.Method; - import scala.jdk.javaapi.CollectionConverters; /** - * Bindings are sorted to categories. Every category is sorted alphabetically. - * Categories are roughly: + * Bindings are sorted to categories. Every category is sorted alphabetically. Categories are + * roughly: + * *
    - *
  • Types
  • - *
  • Instance and static methods on types
  • - *
  • Module methods
  • - *
  • Extension and conversion methods
  • + *
  • Types + *
  • Instance and static methods on types + *
  • Module methods + *
  • Extension and conversion methods *
*/ public final class BindingSorter { private BindingSorter() {} - /** - * Returns sorted list of bindings defined on the given {@code moduleIr}. - */ + /** Returns sorted list of bindings defined on the given {@code moduleIr}. */ public static List sortedBindings(Module moduleIr) { - var visibleBindings = moduleIr.bindings().filter(b -> b instanceof Method m ? !m.isPrivate() : true); + var visibleBindings = + moduleIr.bindings().filter(b -> b instanceof Method m ? !m.isPrivate() : true); var bindings = CollectionConverters.asJava(visibleBindings); var comparator = new BindingComparator(moduleIr); return bindings.stream().sorted(comparator).toList(); @@ -40,12 +38,10 @@ public static List sortConstructors(List const return constructors.stream().sorted(comparator).toList(); } - private static int compareTypes(Type type1, Type type2) { return type1.name().name().compareTo(type2.name().name()); } - private static final class BindingComparator implements java.util.Comparator { private final Module moduleIr; private Set typeNames; @@ -57,10 +53,8 @@ private BindingComparator(Module moduleIr) { @Override public int compare(Definition def1, Definition def2) { return switch (def1) { - case Method method1 when def2 instanceof Method methods -> - compareMethods(method1, methods); - case Type type1 when def2 instanceof Type type2 -> - compareTypes(type1, type2); + case Method method1 when def2 instanceof Method methods -> compareMethods(method1, methods); + case Type type1 when def2 instanceof Type type2 -> compareTypes(type1, type2); case Type type1 when def2 instanceof Method method2 -> compareTypeAndMethod(type1, method2); case Method method1 when def2 instanceof Type type2 -> -compareTypeAndMethod(type2, method1); @@ -84,11 +78,10 @@ private int compareTypeAndMethod(Type type, Method method) { return -1; } - private int compareMethods(Method method1, Method method2) { return switch (method1) { - case - Method.Explicit explicitMethod1 when method2 instanceof Method.Explicit explicitMethod2 -> { + case Method.Explicit explicitMethod1 + when method2 instanceof Method.Explicit explicitMethod2 -> { if (explicitMethod1.isPrivate() != explicitMethod2.isPrivate()) { if (explicitMethod1.isPrivate()) { yield 1; @@ -111,7 +104,9 @@ private int compareMethods(Method method1, Method method2) { var typeName2 = type2.get().name(); if (typeName1.equals(typeName2)) { // Methods are defined on the same type - yield explicitMethod1.methodName().name() + yield explicitMethod1 + .methodName() + .name() .compareTo(explicitMethod2.methodName().name()); } else { yield type1.get().name().compareTo(type2.get().name()); @@ -123,23 +118,23 @@ private int compareMethods(Method method1, Method method2) { yield 1; } assert !type1.isDefined() && !type2.isDefined(); - yield explicitMethod1.methodName().name() - .compareTo(explicitMethod2.methodName().name()); + yield explicitMethod1.methodName().name().compareTo(explicitMethod2.methodName().name()); } // Comparison of conversion methods is not supported. case Method.Conversion conversion1 when method2 instanceof Method.Conversion conversion2 -> 0; case Method.Explicit explicit when method2 instanceof Method.Conversion -> -1; case Method.Conversion conversion when method2 instanceof Method.Explicit -> 1; - default -> throw new AssertionError( - "Unexpected type: method1=%s, method2=%s".formatted(method1.getClass(), - method2.getClass())); + default -> + throw new AssertionError( + "Unexpected type: method1=%s, method2=%s" + .formatted(method1.getClass(), method2.getClass())); }; } /** - * An extension method is a method that is defined on a type that is defined outside the - * current module. + * An extension method is a method that is defined on a type that is defined outside the current + * module. */ private boolean isExtensionMethod(Method method) { if (method.typeName().isDefined()) { @@ -152,18 +147,22 @@ private boolean isExtensionMethod(Method method) { private Set typeNamesInModule() { if (typeNames == null) { typeNames = new HashSet<>(); - moduleIr.bindings().foreach(binding -> { - if (binding instanceof Definition.Type type) { - typeNames.add(type.name().name()); - } - return null; - }); + moduleIr + .bindings() + .foreach( + binding -> { + if (binding instanceof Definition.Type type) { + typeNames.add(type.name().name()); + } + return null; + }); } return typeNames; } } - private static final class ConstructorComparator implements java.util.Comparator { + private static final class ConstructorComparator + implements java.util.Comparator { @Override public int compare(Data cons1, Data cons2) { diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/AmbiguousImportsAnalysis.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/AmbiguousImportsAnalysis.java index 05cbf334ba65..393de4ce8093 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/AmbiguousImportsAnalysis.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/AmbiguousImportsAnalysis.java @@ -4,7 +4,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.enso.scala.wrapper.ScalaConversions; import org.enso.compiler.context.InlineContext; import org.enso.compiler.context.ModuleContext; import org.enso.compiler.core.CompilerError; @@ -23,6 +22,7 @@ import org.enso.compiler.pass.IRProcessingPass; import org.enso.compiler.pass.MiniIRPass; import org.enso.compiler.pass.MiniPassFactory; +import org.enso.scala.wrapper.ScalaConversions; import scala.collection.immutable.Seq; import scala.jdk.javaapi.CollectionConverters; @@ -76,7 +76,6 @@ public MiniIRPass createForInlineCompilation(InlineContext inlineContext) { return null; } - private static final class Mini extends MiniIRPass { private final EncounteredSymbols encounteredSymbols = new EncounteredSymbols(); private final BindingsMap bindingsMap; @@ -101,15 +100,18 @@ public Expression transformExpression(Expression expr) { @Override public Module transformModule(Module moduleIr) { var newImports = new ArrayList(); - moduleIr.imports().foreach(imp -> { - var errs = analyseAmbiguousSymbols(imp); - if (!errs.isEmpty()) { - newImports.addAll(errs); - } else { - newImports.add(imp); - } - return null; - }); + moduleIr + .imports() + .foreach( + imp -> { + var errs = analyseAmbiguousSymbols(imp); + if (!errs.isEmpty()) { + newImports.addAll(errs); + } else { + newImports.add(imp); + } + return null; + }); return moduleIr.copy( CollectionConverters.asScala(newImports).toList(), moduleIr.exports(), @@ -142,7 +144,8 @@ private List analyseAmbiguousSymbols(Import imp) { var resolvedNames = resolution.toOption().get(); for (var resolvedName : CollectionConverters.asJava(resolvedNames)) { var symbolPath = resolvedName.qualifiedName().toString(); - tryAddEncounteredSymbol(impMod, symbolName, symbolPath, resolvedName, errorsForImport); + tryAddEncounteredSymbol( + impMod, symbolName, symbolPath, resolvedName, errorsForImport); } } } @@ -151,18 +154,22 @@ private List analyseAmbiguousSymbols(Import imp) { // Import all symbols case Import.Module impMod when impMod.isAll() && !impMod.isSynthetic() -> { var importTargets = getImportTargets(impMod); - // Names of the symbols that are exported by a module or a type referred to via importTarget - var exportedSymbolNames = importTargets.stream() - .flatMap(target -> { - var expSymbols = target.exportedSymbols().keySet().toList(); - return CollectionConverters.asJava(expSymbols).stream(); - }); + // Names of the symbols that are exported by a module or a type referred to via + // importTarget + var exportedSymbolNames = + importTargets.stream() + .flatMap( + target -> { + var expSymbols = target.exportedSymbols().keySet().toList(); + return CollectionConverters.asJava(expSymbols).stream(); + }); List symbolsToIterate; if (impMod.hiddenNames().isDefined()) { var hiddenNames = impMod.hiddenNames().get().map(Literal::name); - symbolsToIterate = exportedSymbolNames - .filter(exportedSymName -> !hiddenNames.contains(exportedSymName)) - .toList(); + symbolsToIterate = + exportedSymbolNames + .filter(exportedSymName -> !hiddenNames.contains(exportedSymName)) + .toList(); } else { symbolsToIterate = exportedSymbolNames.toList(); } @@ -180,7 +187,8 @@ private List analyseAmbiguousSymbols(Import imp) { } var resolvedName = resolvedNames.head(); var symbolPath = resolvedName.qualifiedName().toString(); - tryAddEncounteredSymbol(impMod, symbolName, symbolPath, resolvedName, errorsForImport); + tryAddEncounteredSymbol( + impMod, symbolName, symbolPath, resolvedName, errorsForImport); } } } @@ -200,7 +208,8 @@ private List analyseAmbiguousSymbols(Import imp) { } case Polyglot polyglotImp -> { - var symbolName = polyglotImp.rename().getOrElse(() -> polyglotImp.entity().getVisibleName()); + var symbolName = + polyglotImp.rename().getOrElse(() -> polyglotImp.entity().getVisibleName()); String symbolPath; if (polyglotImp.entity() instanceof Polyglot.Java javaEntity) { symbolPath = javaEntity.packageName() + "." + javaEntity.className(); @@ -216,9 +225,10 @@ private List analyseAmbiguousSymbols(Import imp) { } /** - * Tries to add the encountered symbol to the encountered symbols map. If it is already contained - * in the map, checks whether the underlying entity path is the same as the original entity path. - * Based on that, either attaches a warning for a duplicated import, or returns an {@link ImportExport}. + * Tries to add the encountered symbol to the encountered symbols map. If it is already + * contained in the map, checks whether the underlying entity path is the same as the original + * entity path. Based on that, either attaches a warning for a duplicated import, or returns an + * {@link ImportExport}. * * @param currentImport Currently iterated import * @param symbolName Name of the symbol that is about to be processed @@ -235,27 +245,25 @@ private void tryAddEncounteredSymbol( encounteredSymbols.addSymbol(currentImport, symbolName, symbolPath, resolvedName); } else { var encounteredFullName = encounteredSymbols.getPathForSymbol(symbolName); - var encounteredResolution = - encounteredSymbols.getResolvedNameForSymbol(symbolName); + var encounteredResolution = encounteredSymbols.getResolvedNameForSymbol(symbolName); var originalImport = encounteredSymbols.getOriginalImportForSymbol(symbolName); - if (symbolPath.equals(encounteredFullName) && !areResolvedNamesAllowedToClash(resolvedName, encounteredResolution)) { + if (symbolPath.equals(encounteredFullName) + && !areResolvedNamesAllowedToClash(resolvedName, encounteredResolution)) { // symbolName is already imported with the same symbolPath --> attach warning. var warn = createWarningForDuplicatedImport(originalImport, currentImport, symbolName); currentImport.getDiagnostics().add(warn); } else { // There is an encountered symbol with different physical path than symbolPath. - if (encounteredResolution instanceof BindingsMap.ResolvedMethod resMethod && - resMethod.methodName().equals(symbolName)) { - // This is a valid ambiguous case - in previously encountered import, the symbol was resolved + if (encounteredResolution instanceof BindingsMap.ResolvedMethod resMethod + && resMethod.methodName().equals(symbolName)) { + // This is a valid ambiguous case - in previously encountered import, the symbol was + // resolved // to either an extension, static, or conversion method. return; } else { - var error = createErrorForAmbiguousImport( - originalImport, - encounteredFullName, - currentImport, - symbolName, - symbolPath); + var error = + createErrorForAmbiguousImport( + originalImport, encounteredFullName, currentImport, symbolName, symbolPath); errors.add(error); } } @@ -263,15 +271,9 @@ private void tryAddEncounteredSymbol( } private static Warning createWarningForDuplicatedImport( - Import originalImport, - Import duplicatingImport, - String duplicatedSymbol - ) { + Import originalImport, Import duplicatingImport, String duplicatedSymbol) { return new Warning.DuplicatedImport( - duplicatingImport.identifiedLocation(), - originalImport, - duplicatedSymbol - ); + duplicatingImport.identifiedLocation(), originalImport, duplicatedSymbol); } private ImportExport createErrorForAmbiguousImport( @@ -283,34 +285,31 @@ private ImportExport createErrorForAmbiguousImport( return ImportExport.apply( duplicatingImport, new ImportExport.AmbiguousImport( - originalImport, - originalSymbolPath, - ambiguousSymbol, - ambiguousSymbolPath - ), - new MetadataStorage() - ); + originalImport, originalSymbolPath, ambiguousSymbol, ambiguousSymbolPath), + new MetadataStorage()); } /** - * {@link org.enso.compiler.data.BindingsMap.ResolvedModuleMethod} and - * {@link org.enso.compiler.data.BindingsMap.ResolvedExtensionMethod} are allowed to - * clash - they are allowed to have the same fully qualified name, and no - * "duplicate import" warning should be generated for them. + * {@link org.enso.compiler.data.BindingsMap.ResolvedModuleMethod} and {@link + * org.enso.compiler.data.BindingsMap.ResolvedExtensionMethod} are allowed to clash - they are + * allowed to have the same fully qualified name, and no "duplicate import" warning should be + * generated for them. */ private static boolean areResolvedNamesAllowedToClash(ResolvedName name1, ResolvedName name2) { - if (name1 instanceof BindingsMap.ResolvedExtensionMethod && - name2 instanceof BindingsMap.ResolvedExtensionMethod) { + if (name1 instanceof BindingsMap.ResolvedExtensionMethod + && name2 instanceof BindingsMap.ResolvedExtensionMethod) { throw new AssertionError("Two extension methods with the same name should not be allowed."); } - if (name1 instanceof BindingsMap.ResolvedModuleMethod && - name2 instanceof BindingsMap.ResolvedModuleMethod) { + if (name1 instanceof BindingsMap.ResolvedModuleMethod + && name2 instanceof BindingsMap.ResolvedModuleMethod) { throw new AssertionError("Two module methods with the same name should not be allowed."); } - if (name1 instanceof BindingsMap.ResolvedExtensionMethod && name2 instanceof BindingsMap.ResolvedModuleMethod) { + if (name1 instanceof BindingsMap.ResolvedExtensionMethod + && name2 instanceof BindingsMap.ResolvedModuleMethod) { return true; } - if (name1 instanceof BindingsMap.ResolvedModuleMethod && name2 instanceof BindingsMap.ResolvedExtensionMethod) { + if (name1 instanceof BindingsMap.ResolvedModuleMethod + && name2 instanceof BindingsMap.ResolvedExtensionMethod) { return true; } return false; @@ -326,27 +325,24 @@ private List getImportTargets(Import imp) { } } - /** @param symbolPath Fully qualified name of the symbol, i.e., its physical path. + /** + * @param symbolPath Fully qualified name of the symbol, i.e., its physical path. * @param resolvedName The optional resolved name of the symbol. - * @param originalImport The import IR from which the symbol was originally imported. - * i.e. the first encountered import IR that imports the symbol. + * @param originalImport The import IR from which the symbol was originally imported. i.e. the + * first encountered import IR that imports the symbol. */ - private record SymbolTarget( - String symbolPath, - ResolvedName resolvedName, - Import originalImport - ) { + private record SymbolTarget(String symbolPath, ResolvedName resolvedName, Import originalImport) { private SymbolTarget { assert symbolPath != null; assert originalImport != null; } } - - /** For every encountered symbol name, we keep track of the original import from which it was imported, - * along with the entity path. The entity path is vital to decide whether an imported symbol is duplicated - * or ambiguous. - * Note that there are some exceptions that are allowed to be ambiguous, like extension methods. + /** + * For every encountered symbol name, we keep track of the original import from which it was + * imported, along with the entity path. The entity path is vital to decide whether an imported + * symbol is duplicated or ambiguous. Note that there are some exceptions that are allowed to be + * ambiguous, like extension methods. */ private static final class EncounteredSymbols { private final Map symbols = new HashMap<>(); diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/ImportSymbolAnalysis.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/ImportSymbolAnalysis.java index ce7fc568b71e..c83792815f06 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/ImportSymbolAnalysis.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/ImportSymbolAnalysis.java @@ -176,24 +176,26 @@ private static ImportExport createErrorForUnresolvedSymbol( Import imp, BindingsMap.ImportTarget importTarget, Name.Literal unresolvedSymbol) { ImportExport.Reason errorReason = switch (importTarget) { - case BindingsMap.ResolvedModule resMod -> new ImportExport.SymbolDoesNotExist( - unresolvedSymbol.name(), resMod.module().getName().toString()); - case BindingsMap.ResolvedType resType -> new ImportExport.NoSuchConstructor( - resType.tp().name(), unresolvedSymbol.name()); - case BindingsMap.ResolvedConstructor resCons -> new ImportExport.NoSuchConstructor( - resCons.cons().name(), unresolvedSymbol.name()); - case BindingsMap.ResolvedModuleMethod resMethod -> new ImportExport.NoSuchModuleMethod( - resMethod.method().name(), unresolvedSymbol.name()); - case BindingsMap.ResolvedExtensionMethod extMethod -> new ImportExport - .NoSuchStaticMethod( - extMethod.module().getName().toString(), - extMethod.staticMethod().tpName(), - unresolvedSymbol.name()); - case BindingsMap.ResolvedConversionMethod convMethod -> new ImportExport - .NoSuchConversionMethod( - convMethod.module().getName().toString(), - convMethod.conversionMethod().targetTpName(), - convMethod.conversionMethod().sourceTpName()); + case BindingsMap.ResolvedModule resMod -> + new ImportExport.SymbolDoesNotExist( + unresolvedSymbol.name(), resMod.module().getName().toString()); + case BindingsMap.ResolvedType resType -> + new ImportExport.NoSuchConstructor(resType.tp().name(), unresolvedSymbol.name()); + case BindingsMap.ResolvedConstructor resCons -> + new ImportExport.NoSuchConstructor(resCons.cons().name(), unresolvedSymbol.name()); + case BindingsMap.ResolvedModuleMethod resMethod -> + new ImportExport.NoSuchModuleMethod( + resMethod.method().name(), unresolvedSymbol.name()); + case BindingsMap.ResolvedExtensionMethod extMethod -> + new ImportExport.NoSuchStaticMethod( + extMethod.module().getName().toString(), + extMethod.staticMethod().tpName(), + unresolvedSymbol.name()); + case BindingsMap.ResolvedConversionMethod convMethod -> + new ImportExport.NoSuchConversionMethod( + convMethod.module().getName().toString(), + convMethod.conversionMethod().targetTpName(), + convMethod.conversionMethod().sourceTpName()); default -> throw new IllegalStateException("Unexpected value: " + importTarget); }; return new ImportExport(imp, errorReason, new MetadataStorage()); diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/TailCall.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/TailCall.java index 1a50c047e7fb..153e12a71104 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/TailCall.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/TailCall.java @@ -169,17 +169,24 @@ private Void updateModuleBinding(Definition moduleDefinition) { switch (moduleDefinition) { case Method.Conversion method -> markAsTail(method); case Method.Explicit method -> markAsTail(method); - case Method.Binding b -> throw new CompilerError( - "Sugared method definitions should not occur during tail call " + "analysis."); + case Method.Binding b -> + throw new CompilerError( + "Sugared method definitions should not occur during tail call " + "analysis."); case Definition.Type t -> markAsTail(t); - case Definition.SugaredType st -> throw new CompilerError( - "Complex type definitions should not be present during " + "tail call analysis."); - case Comment.Documentation cd -> throw new CompilerError( - "Documentation should not exist as an entity during tail call analysis."); - case Type.Ascription ta -> throw new CompilerError( - "Type signatures should not exist at the top level during " + "tail call analysis."); - case Name.BuiltinAnnotation ba -> throw new CompilerError( - "Annotations should already be associated by the point of " + "tail call analysis."); + case Definition.SugaredType st -> + throw new CompilerError( + "Complex type definitions should not be present during " + "tail call analysis."); + case Comment.Documentation cd -> + throw new CompilerError( + "Documentation should not exist as an entity during tail call analysis."); + case Type.Ascription ta -> + throw new CompilerError( + "Type signatures should not exist at the top level during " + + "tail call analysis."); + case Name.BuiltinAnnotation ba -> + throw new CompilerError( + "Annotations should already be associated by the point of " + + "tail call analysis."); case Name.GenericAnnotation ann -> markAsTail(ann); default -> {} } @@ -249,8 +256,8 @@ private void collectTailCandidatesExpression( case Case caseExpr -> collectTailCandidatesCase(caseExpr, tailCandidates); case Application app -> collectTailCandidatesApplication(app, tailCandidates); case Name name -> collectTailCandidatesName(name, tailCandidates); - case Comment c -> throw new CompilerError( - "Comments should not be present during tail call analysis."); + case Comment c -> + throw new CompilerError("Comments should not be present during tail call analysis."); case Expression.Block b -> { if (isInTailPos) { tailCandidates.put(b.returnValue(), true); @@ -281,8 +288,8 @@ private void collectTailCandidatesName(Name name, java.util.Map tai private void collectTailCandidatesApplication( Application application, java.util.Map tailCandidates) { switch (application) { - case Application.Prefix p -> p.arguments() - .foreach(a -> collectTailCandidatesCallArg(a, tailCandidates)); + case Application.Prefix p -> + p.arguments().foreach(a -> collectTailCandidatesCallArg(a, tailCandidates)); case Application.Force f -> { if (isInTailPos) { tailCandidates.put(f.target(), true); @@ -304,8 +311,8 @@ private Void collectTailCandidatesCallArg( CallArgument argument, java.util.Map tailCandidates) { switch (argument) { case CallArgument.Specified ca -> - // Note [Call Argument Tail Position] - tailCandidates.put(ca.value(), true); + // Note [Call Argument Tail Position] + tailCandidates.put(ca.value(), true); default -> {} } return null; @@ -391,8 +398,9 @@ private void collectTailCandicateFunction( tailCandidates.put(l.body(), true); } } - default -> throw new CompilerError( - "Function sugar should not be present during tail call analysis."); + default -> + throw new CompilerError( + "Function sugar should not be present during tail call analysis."); } } } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCheckAlgorithm.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCheckAlgorithm.java index e54e9e3a25fc..b3d714060db2 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCheckAlgorithm.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCheckAlgorithm.java @@ -99,15 +99,16 @@ public final R extractAscribedType(Expression t) throws E { } case Application.Prefix p -> extractAscribedType(p.function()); case Type.Function fn -> - // find a function type - forFunction(fn); + // find a function type + forFunction(fn); case Type.Error typeWithError -> - // When checking a `a ! b` type, we ignore the error part as it is only used for documentation - // purposes and is not checked. - extractAscribedType(typeWithError.typed()); + // When checking a `a ! b` type, we ignore the error part as it is only used for + // documentation + // purposes and is not checked. + extractAscribedType(typeWithError.typed()); case Type.Context typeInContext -> - // Type contexts aren't currently really used. But we should still check the base type. - extractAscribedType(typeInContext.typed()); + // Type contexts aren't currently really used. But we should still check the base type. + extractAscribedType(typeInContext.typed()); case Resolution err -> forError(err); default -> { var res = diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCompatibility.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCompatibility.java index fa211a2ac3ef..86004e90ee4a 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCompatibility.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeCompatibility.java @@ -150,10 +150,10 @@ boolean mayBeFunctionLike(TypeRepresentation type) { return switch (type) { case TypeRepresentation.TopType top -> true; - case TypeRepresentation.SumType sumType -> sumType.types().stream() - .anyMatch(this::mayBeFunctionLike); - case TypeRepresentation.IntersectionType intersectionType -> intersectionType.types().stream() - .anyMatch(this::mayBeFunctionLike); + case TypeRepresentation.SumType sumType -> + sumType.types().stream().anyMatch(this::mayBeFunctionLike); + case TypeRepresentation.IntersectionType intersectionType -> + intersectionType.types().stream().anyMatch(this::mayBeFunctionLike); default -> false; }; } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeInferenceSignatures.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeInferenceSignatures.java index 48b169cce94a..835f5cc1e15a 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeInferenceSignatures.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeInferenceSignatures.java @@ -123,7 +123,7 @@ public Expression runExpression(Expression ir, InlineContext inlineContext) { private TypeRepresentation resolveTopLevelTypeSignature( Expression body, boolean keepSelfArgument) { return switch (body) { - // Combine argument types with ascribed type (if available) for a function type signature + // Combine argument types with ascribed type (if available) for a function type signature case Function.Lambda lambda -> { boolean hasAnyDefaults = lambda.arguments().find((arg) -> arg.defaultValue().isDefined()).isDefined(); @@ -176,8 +176,8 @@ private TypeRepresentation resolveTopLevelTypeSignature( yield TypeRepresentation.buildFunction(ScalaConversions.asJava(argTypesScala), returnType); } - // Otherwise, we encountered a 0-argument method, so its type is just its return type (if - // its known). + // Otherwise, we encountered a 0-argument method, so its type is just its return type (if + // its known). default -> findReturnTypeAscription(body); }; } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypePropagation.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypePropagation.java index 6a331c1264c6..9024d2020b59 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypePropagation.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypePropagation.java @@ -244,13 +244,13 @@ private TypeRepresentation processName( private TypeRepresentation processLiteral(Literal literal) { return switch (literal) { - case Literal.Number number -> number.isFractional() - ? BuiltinTypes.FLOAT - : BuiltinTypes.INTEGER; + case Literal.Number number -> + number.isFractional() ? BuiltinTypes.FLOAT : BuiltinTypes.INTEGER; case Literal.Text text -> BuiltinTypes.TEXT; - // This branch is needed only because Java is unable to infer that the match is exhaustive - default -> throw new IllegalStateException( - "Impossible - unknown literal type: " + literal.getClass().getCanonicalName()); + // This branch is needed only because Java is unable to infer that the match is exhaustive + default -> + throw new IllegalStateException( + "Impossible - unknown literal type: " + literal.getClass().getCanonicalName()); }; } @@ -468,8 +468,8 @@ private TypeRepresentation processUnresolvedSymbolApplication( return methodTypeResolver.resolveMethod(TypeScopeReference.ANY, function.name()); } - // This is not calling this function, instead it is calling the _method_ represented by the - // UnresolvedSymbol on this Function object. + // This is not calling this function, instead it is calling the _method_ represented by the + // UnresolvedSymbol on this Function object. case TypeRepresentation.ArrowType functionAsObject -> { var typeScope = TypeScopeReference.atomType(functionAsObject.getAssociatedType()); var resolvedMethod = methodTypeResolver.resolveMethod(typeScope, function.name()); @@ -556,8 +556,8 @@ protected TypeRepresentation resolveGlobalName( case BindingsMap.ResolvedType tpe -> typeResolver.resolvedTypeAsTypeObject(tpe); - case BindingsMap.ResolvedModule mod -> new TypeRepresentation.ModuleReference( - mod.qualifiedName()); + case BindingsMap.ResolvedModule mod -> + new TypeRepresentation.ModuleReference(mod.qualifiedName()); default -> { logger.trace( diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeResolver.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeResolver.java index fcc8841366e1..6f30b1eef94d 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeResolver.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/analyse/types/TypeResolver.java @@ -38,21 +38,21 @@ public TypeRepresentation resolveTypeExpression(Expression type) { yield new TypeRepresentation.IntersectionType(List.of(lhs, rhs)); } - // We could extract more info form function, but we deliberately do not. - // This is because our ascriptions (x : A -> B) only check (x.is_a Function), so all we get - // is that it is a - // function with at least one argument (and we can't even tell its full arity). - // Later, we could extract this as some kind of secondary metadata, but currently we do not - // because it could be - // misleading - this property is _not_ guaranteed at runtime as other ascriptions are. - // Functions not matching - // this type will still be allowed. That's why we return the more generic type that covers - // everything that the - // check actually lets through. - case Type.Function function -> new TypeRepresentation.ArrowType( - TypeRepresentation.UNKNOWN, TypeRepresentation.ANY); - - // We just ignore the error part for now as it's not really checked anywhere. + // We could extract more info form function, but we deliberately do not. + // This is because our ascriptions (x : A -> B) only check (x.is_a Function), so all we get + // is that it is a + // function with at least one argument (and we can't even tell its full arity). + // Later, we could extract this as some kind of secondary metadata, but currently we do not + // because it could be + // misleading - this property is _not_ guaranteed at runtime as other ascriptions are. + // Functions not matching + // this type will still be allowed. That's why we return the more generic type that covers + // everything that the + // check actually lets through. + case Type.Function function -> + new TypeRepresentation.ArrowType(TypeRepresentation.UNKNOWN, TypeRepresentation.ANY); + + // We just ignore the error part for now as it's not really checked anywhere. case Type.Error error -> resolveTypeExpression(error.typed()); case Name.Qualified qualified -> { diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/desugar/SectionsToBinOp.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/desugar/SectionsToBinOp.java index a2fee437167e..a69577d16793 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/desugar/SectionsToBinOp.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/desugar/SectionsToBinOp.java @@ -191,24 +191,24 @@ public Expression transformExpression(Expression ir) { .build(); } - /* Note [Blanks in Sections] - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * While the naiive compositional translation of `(- _)` first translates - * the section into a function applying `-` to two arguments, one of which - * is a blank, the compositional nature of the blanks translation actually - * works against us here. - * - * As the `LambdaShorthandToLambda` pass can only operate on the - * application with the blanks, it can't know to push the blank outside - * that application chain. To that end, we have to handle this case - * specially here instead. What we want it to translate to is as follows: - * - * `(- _)` == `x -> (- x)` == `x -> y -> y - x` - * - * We implement this special case here. - * - * The same is true of left sections. - */ + /* Note [Blanks in Sections] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * While the naiive compositional translation of `(- _)` first translates + * the section into a function applying `-` to two arguments, one of which + * is a blank, the compositional nature of the blanks translation actually + * works against us here. + * + * As the `LambdaShorthandToLambda` pass can only operate on the + * application with the blanks, it can't know to push the blank outside + * that application chain. To that end, we have to handle this case + * specially here instead. What we want it to translate to is as follows: + * + * `(- _)` == `x -> (- x)` == `x -> y -> y - x` + * + * We implement this special case here. + * + * The same is true of left sections. + */ case Section.Right sectionRight -> { var arg = sectionRight.arg(); diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/ShadowedPatternFields.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/ShadowedPatternFields.java index d5a344135ff1..a449fd6f1f0f 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/ShadowedPatternFields.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/ShadowedPatternFields.java @@ -164,8 +164,9 @@ private Pattern go(Pattern pattern, Set seenNames, Map lastS yield typed; } } - case Pattern.Documentation doc -> throw new CompilerError( - "Branch documentation should be desugared at an earlier stage."); + case Pattern.Documentation doc -> + throw new CompilerError( + "Branch documentation should be desugared at an earlier stage."); default -> pattern; }; } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/unusedimports/UnusedImports.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/unusedimports/UnusedImports.java index 9cc519415193..e99e5acaa2cf 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/unusedimports/UnusedImports.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/lint/unusedimports/UnusedImports.java @@ -161,7 +161,7 @@ private boolean isImportedSymbolUsed( var isTypeUsed = usedSymbolsForImp.contains(typeName); yield isTypeUsed; } - // If any of the Type's constructor is used, the whole type is used. + // If any of the Type's constructor is used, the whole type is used. case ResolvedType type -> { var constructors = asJava(type.tp().members()); var typeName = type.qualifiedName(); diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/resolve/MethodDefinitions.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/resolve/MethodDefinitions.java index 853b6ef9562f..92c3a1759b87 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/resolve/MethodDefinitions.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/pass/resolve/MethodDefinitions.java @@ -141,10 +141,11 @@ public Module transformModule(Module moduleIr) { Name resolvedName = switch (sourceTypeExpr) { case Name name -> resolveType(name, bindingsMap); - default -> new Conversion( - sourceTypeExpr, - UnsupportedSourceType$.MODULE$, - new MetadataStorage()); + default -> + new Conversion( + sourceTypeExpr, + UnsupportedSourceType$.MODULE$, + new MetadataStorage()); }; var resolvedMethod = conversionMethod.copy( @@ -157,8 +158,9 @@ public Module transformModule(Module moduleIr) { conversionMethod.id()); yield resolvedMethod; } - default -> throw new CompilerError( - "Unexpected method type in MethodDefinitions pass."); + default -> + throw new CompilerError( + "Unexpected method type in MethodDefinitions pass."); }; } else { return def; diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/ImportResolverForIR.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/ImportResolverForIR.java index c041dfeda1c3..69713e63d886 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/ImportResolverForIR.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/ImportResolverForIR.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.util.Objects; - import java.util.stream.Collectors; import org.enso.common.CompilationStage; import org.enso.compiler.Compiler; @@ -16,29 +15,28 @@ import org.enso.compiler.data.BindingsMap.ImportTarget; import org.enso.compiler.data.BindingsMap.ResolvedConstructor; import org.enso.compiler.data.BindingsMap.ResolvedConversionMethod; +import org.enso.compiler.data.BindingsMap.ResolvedExtensionMethod; import org.enso.compiler.data.BindingsMap.ResolvedImport; import org.enso.compiler.data.BindingsMap.ResolvedModuleMethod; -import org.enso.compiler.data.BindingsMap.ResolvedExtensionMethod; import org.enso.compiler.data.BindingsMap.ResolvedType; import org.enso.editions.LibraryName; - import scala.Option; import scala.Tuple2; import scala.collection.immutable.List; import scala.jdk.CollectionConverters; -abstract class ImportResolverForIR extends ImportResolverAlgorithm< - Tuple2>, - Module, - Import.Module, - Export.Module, - ResolvedType, - CompilerContext.Module, - ResolvedConstructor, - ResolvedModuleMethod, - ResolvedExtensionMethod, - ResolvedConversionMethod -> { +abstract class ImportResolverForIR + extends ImportResolverAlgorithm< + Tuple2>, + Module, + Import.Module, + Export.Module, + ResolvedType, + CompilerContext.Module, + ResolvedConstructor, + ResolvedModuleMethod, + ResolvedExtensionMethod, + ResolvedConversionMethod> { abstract Compiler getCompiler(); @Override @@ -83,10 +81,16 @@ protected String nameForConversionMethod(ResolvedConversionMethod resolvedConver @Override protected final java.util.List exportsFor(Module module, String impName) { - java.util.List exp = CollectionConverters.SeqHasAsJava(module.exports()).asJava().stream().map(e -> switch (e) { - case Export.Module ex when ex.name().name().equals(impName) -> ex; - case null, default -> null; - }).filter(Objects::nonNull).toList(); + java.util.List exp = + CollectionConverters.SeqHasAsJava(module.exports()).asJava().stream() + .map( + e -> + switch (e) { + case Export.Module ex when ex.name().name().equals(impName) -> ex; + case null, default -> null; + }) + .filter(Objects::nonNull) + .toList(); return exp; } @@ -112,24 +116,32 @@ protected final java.util.List definedEntities(Import. var mod = optionMod.get(); compiler.ensureParsed(mod); var bindingsMap = loadBindingsMap(mod); - var entitiesStream = bindingsMap.definedEntities().map(e -> switch (e) { - case BindingsMap.Type t -> { - assert e.name().equals(t.name()) : e.name() + " != " + t.name(); - var res = new ResolvedType(new BindingsMap$ModuleReference$Concrete(mod), t); - assert e.name().equals(res.tp().name()) : e.name() + " != " + res.tp().name(); - yield res; - } - case null, default -> null; - }).filter(Objects::nonNull); + var entitiesStream = + bindingsMap + .definedEntities() + .map( + e -> + switch (e) { + case BindingsMap.Type t -> { + assert e.name().equals(t.name()) : e.name() + " != " + t.name(); + var res = + new ResolvedType(new BindingsMap$ModuleReference$Concrete(mod), t); + assert e.name().equals(res.tp().name()) + : e.name() + " != " + res.tp().name(); + yield res; + } + case null, default -> null; + }) + .filter(Objects::nonNull); var entities = CollectionConverters.SeqHasAsJava(entitiesStream).asJava(); return entities; } /** * Returns list of constructors for the given import. - * @param imp The import is treated as an import of a constructor from a type. - * The last part is constructor, the second to last is type, - * the third to last is module. + * + * @param imp The import is treated as an import of a constructor from a type. The last part is + * constructor, the second to last is type, the third to last is module. * @return null if the import is not a constructor import. */ @Override @@ -139,10 +151,7 @@ protected java.util.List definedConstructors(Import.Module return null; } var typeName = parts.get(parts.size() - 2); - var modFullName = parts - .stream() - .limit(parts.size() - 2) - .collect(Collectors.joining(".")); + var modFullName = parts.stream().limit(parts.size() - 2).collect(Collectors.joining(".")); var compiler = getCompiler(); var optionMod = compiler.getModule(modFullName); if (optionMod.isEmpty()) { @@ -151,27 +160,25 @@ protected java.util.List definedConstructors(Import.Module var mod = optionMod.get(); compiler.ensureParsed(mod); var bindingsMap = loadBindingsMap(mod); - var foundType = scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()) - .stream() - .map(e -> { - if (e instanceof BindingsMap.Type tp) { - return tp; - } - return null; - }) - .filter(Objects::nonNull) - .filter(tp -> tp.name().equals(typeName)) - .findFirst(); + var foundType = + scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()).stream() + .map( + e -> { + if (e instanceof BindingsMap.Type tp) { + return tp; + } + return null; + }) + .filter(Objects::nonNull) + .filter(tp -> tp.name().equals(typeName)) + .findFirst(); if (foundType.isEmpty()) { return null; } var tp = foundType.get(); - var resolvedType = new BindingsMap.ResolvedType( - new BindingsMap$ModuleReference$Concrete(mod), - tp - ); - return scala.jdk.javaapi.CollectionConverters.asJava(tp.members()) - .stream() + var resolvedType = + new BindingsMap.ResolvedType(new BindingsMap$ModuleReference$Concrete(mod), tp); + return scala.jdk.javaapi.CollectionConverters.asJava(tp.members()).stream() .map(cons -> new ResolvedConstructor(resolvedType, cons)) .collect(Collectors.toUnmodifiableList()); } @@ -184,10 +191,7 @@ protected java.util.List definedModuleMethods(Import.Modul } var modMethodNameIdx = parts.size() - 1; var modMethodName = parts.get(modMethodNameIdx); - var modFullName = parts - .stream() - .limit(modMethodNameIdx) - .collect(Collectors.joining(".")); + var modFullName = parts.stream().limit(modMethodNameIdx).collect(Collectors.joining(".")); var compiler = getCompiler(); var optionMod = compiler.getModule(modFullName); if (optionMod.isEmpty()) { @@ -196,16 +200,21 @@ protected java.util.List definedModuleMethods(Import.Modul var mod = optionMod.get(); compiler.ensureParsed(mod); var bindingsMap = loadBindingsMap(mod); - var modMethods = scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()) - .stream() - .filter(definedEntity -> { - if (definedEntity instanceof BindingsMap.ModuleMethod moduleMethod) { - return moduleMethod.name().equals(modMethodName); - } - return false; - }) - .map(entity -> new ResolvedModuleMethod(new BindingsMap$ModuleReference$Concrete(mod), (BindingsMap.ModuleMethod) entity)) - .collect(Collectors.toUnmodifiableList()); + var modMethods = + scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()).stream() + .filter( + definedEntity -> { + if (definedEntity instanceof BindingsMap.ModuleMethod moduleMethod) { + return moduleMethod.name().equals(modMethodName); + } + return false; + }) + .map( + entity -> + new ResolvedModuleMethod( + new BindingsMap$ModuleReference$Concrete(mod), + (BindingsMap.ModuleMethod) entity)) + .collect(Collectors.toUnmodifiableList()); return modMethods; } @@ -217,10 +226,7 @@ protected java.util.List definedExtensionMethods(Import } var modMethodNameIdx = parts.size() - 1; var modMethodName = parts.get(modMethodNameIdx); - var modFullName = parts - .stream() - .limit(modMethodNameIdx) - .collect(Collectors.joining(".")); + var modFullName = parts.stream().limit(modMethodNameIdx).collect(Collectors.joining(".")); var compiler = getCompiler(); var optionMod = compiler.getModule(modFullName); if (optionMod.isEmpty()) { @@ -229,16 +235,21 @@ protected java.util.List definedExtensionMethods(Import var mod = optionMod.get(); compiler.ensureParsed(mod); var bindingsMap = loadBindingsMap(mod); - var extensionMethods = scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()) - .stream() - .filter(definedEntity -> { - if (definedEntity instanceof BindingsMap.ExtensionMethod extensionMethod) { - return extensionMethod.name().equals(modMethodName); - } - return false; - }) - .map(entity -> new ResolvedExtensionMethod(new BindingsMap$ModuleReference$Concrete(mod), (BindingsMap.ExtensionMethod) entity)) - .collect(Collectors.toUnmodifiableList()); + var extensionMethods = + scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()).stream() + .filter( + definedEntity -> { + if (definedEntity instanceof BindingsMap.ExtensionMethod extensionMethod) { + return extensionMethod.name().equals(modMethodName); + } + return false; + }) + .map( + entity -> + new ResolvedExtensionMethod( + new BindingsMap$ModuleReference$Concrete(mod), + (BindingsMap.ExtensionMethod) entity)) + .collect(Collectors.toUnmodifiableList()); return extensionMethods; } @@ -250,10 +261,7 @@ protected java.util.List definedConversionMethods(Impo } var modMethodNameIdx = parts.size() - 1; var modMethodName = parts.get(modMethodNameIdx); - var modFullName = parts - .stream() - .limit(modMethodNameIdx) - .collect(Collectors.joining(".")); + var modFullName = parts.stream().limit(modMethodNameIdx).collect(Collectors.joining(".")); var compiler = getCompiler(); var optionMod = compiler.getModule(modFullName); if (optionMod.isEmpty()) { @@ -262,21 +270,27 @@ protected java.util.List definedConversionMethods(Impo var mod = optionMod.get(); compiler.ensureParsed(mod); var bindingsMap = loadBindingsMap(mod); - var conversionMethods = scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()) - .stream() - .filter(definedEntity -> { - if (definedEntity instanceof BindingsMap.ConversionMethod conversionMethod) { - return conversionMethod.methodName().equals(modMethodName); - } - return false; - }) - .map(entity -> new ResolvedConversionMethod(new BindingsMap$ModuleReference$Concrete(mod), (BindingsMap.ConversionMethod) entity)) - .collect(Collectors.toUnmodifiableList()); + var conversionMethods = + scala.jdk.javaapi.CollectionConverters.asJava(bindingsMap.definedEntities()).stream() + .filter( + definedEntity -> { + if (definedEntity instanceof BindingsMap.ConversionMethod conversionMethod) { + return conversionMethod.methodName().equals(modMethodName); + } + return false; + }) + .map( + entity -> + new ResolvedConversionMethod( + new BindingsMap$ModuleReference$Concrete(mod), + (BindingsMap.ConversionMethod) entity)) + .collect(Collectors.toUnmodifiableList()); return conversionMethods; } @Override - protected final CompilerContext.Module loadLibraryModule(LibraryName libraryName, String moduleName) throws IOException { + protected final CompilerContext.Module loadLibraryModule( + LibraryName libraryName, String moduleName) throws IOException { var compiler = this.getCompiler(); var repo = compiler.packageRepository(); var foundLib = repo.ensurePackageIsLoaded(libraryName); @@ -293,74 +307,104 @@ protected final CompilerContext.Module loadLibraryModule(LibraryName libraryName } @Override - protected final Tuple2> createResolvedImport(Import.Module imp, java.util.List exp, CompilerContext.Module m) { - var resolvedModule = new BindingsMap.ResolvedModule(new BindingsMap$ModuleReference$Concrete(m)); - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(resolvedModule))); + protected final Tuple2> createResolvedImport( + Import.Module imp, java.util.List exp, CompilerContext.Module m) { + var resolvedModule = + new BindingsMap.ResolvedModule(new BindingsMap$ModuleReference$Concrete(m)); + var resolvedImport = + new BindingsMap.ResolvedImport( + imp, toScalaList(exp), toScalaList(java.util.List.of(resolvedModule))); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override - protected final Tuple2> createResolvedType(Import.Module imp, java.util.List exp, BindingsMap.ResolvedType typ) { - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(typ))); + protected final Tuple2> createResolvedType( + Import.Module imp, java.util.List exp, BindingsMap.ResolvedType typ) { + var resolvedImport = + new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(typ))); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override - protected Tuple2> createResolvedConstructor(Import.Module imp, - java.util.List exp, ResolvedConstructor cons) { - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(cons))); + protected Tuple2> createResolvedConstructor( + Import.Module imp, java.util.List exp, ResolvedConstructor cons) { + var resolvedImport = + new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(cons))); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override - protected Tuple2> createResolvedModuleMethod(Import.Module imp, - java.util.List exp, ResolvedModuleMethod resolvedModuleMethod) { - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(java.util.List.of(resolvedModuleMethod))); + protected Tuple2> createResolvedModuleMethod( + Import.Module imp, + java.util.List exp, + ResolvedModuleMethod resolvedModuleMethod) { + var resolvedImport = + new BindingsMap.ResolvedImport( + imp, toScalaList(exp), toScalaList(java.util.List.of(resolvedModuleMethod))); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override - protected Tuple2> createResolvedExtensionMethods(Import.Module imp, - java.util.List exp, java.util.List extensionMethods) { - java.util.List importTargets = extensionMethods - .stream() - .map(ImportTarget.class::cast) - .collect(Collectors.toUnmodifiableList()); - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(importTargets)); + protected Tuple2> createResolvedExtensionMethods( + Import.Module imp, + java.util.List exp, + java.util.List extensionMethods) { + java.util.List importTargets = + extensionMethods.stream() + .map(ImportTarget.class::cast) + .collect(Collectors.toUnmodifiableList()); + var resolvedImport = + new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(importTargets)); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override protected Tuple2> createResolvedConversionMethods( - Import.Module imp, java.util.List exp, + Import.Module imp, + java.util.List exp, java.util.List resolvedConversionMethods) { - java.util.List importTargets = resolvedConversionMethods - .stream() - .map(ImportTarget.class::cast) - .collect(Collectors.toUnmodifiableList()); - var resolvedImport = new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(importTargets)); + java.util.List importTargets = + resolvedConversionMethods.stream() + .map(ImportTarget.class::cast) + .collect(Collectors.toUnmodifiableList()); + var resolvedImport = + new BindingsMap.ResolvedImport(imp, toScalaList(exp), toScalaList(importTargets)); return new Tuple2<>(imp, scala.Some.apply(resolvedImport)); } @Override - protected final Tuple2> createErrorPackageCoundNotBeLoaded(Import.Module imp, String impName, String loadingError) { - org.enso.compiler.core.ir.expression.errors.ImportExport importError = new ImportExport(imp, new ImportExport.PackageCouldNotBeLoaded(impName, loadingError), imp.passData(), imp.diagnostics()); + protected final Tuple2> + createErrorPackageCoundNotBeLoaded(Import.Module imp, String impName, String loadingError) { + org.enso.compiler.core.ir.expression.errors.ImportExport importError = + new ImportExport( + imp, + new ImportExport.PackageCouldNotBeLoaded(impName, loadingError), + imp.passData(), + imp.diagnostics()); return new Tuple2<>(importError, Option.empty()); } @Override - protected final Tuple2> createErrorModuleDoesNotExist(Import.Module imp, String impName) { - return new Tuple2<>(new ImportExport(imp, new ImportExport.ModuleDoesNotExist(impName), imp.passData(), imp.diagnostics()), Option.empty()); + protected final Tuple2> createErrorModuleDoesNotExist( + Import.Module imp, String impName) { + return new Tuple2<>( + new ImportExport( + imp, new ImportExport.ModuleDoesNotExist(impName), imp.passData(), imp.diagnostics()), + Option.empty()); } private BindingsMap loadBindingsMap(CompilerContext.Module mod) { var bindingsMap = mod.getBindingsMap(); if (bindingsMap == null) { - getCompiler().context().updateModule(mod, u -> { - u.invalidateCache(); - u.ir(null); - u.compilationStage(CompilationStage.INITIAL); - }); + getCompiler() + .context() + .updateModule( + mod, + u -> { + u.invalidateCache(); + u.ir(null); + u.compilationStage(CompilationStage.INITIAL); + }); getCompiler().ensureParsed(mod, false, false); bindingsMap = mod.getBindingsMap(); } diff --git a/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/exports/ConflictingResolutionsError.java b/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/exports/ConflictingResolutionsError.java index 1f0ad66614ce..4c0f17eaf52f 100644 --- a/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/exports/ConflictingResolutionsError.java +++ b/engine/runtime-compiler/src/main/java/org/enso/compiler/phase/exports/ConflictingResolutionsError.java @@ -50,12 +50,10 @@ private static String resolvedNameToString(ResolvedName resolvedName) { } case ResolvedMethod resolvedMethod -> "Method '" + resolvedMethod.qualifiedName() + "'"; case ResolvedModule resolvedModule -> "Module '" + resolvedModule.qualifiedName() + "'"; - case ResolvedPolyglotField resolvedPolyglotField -> "Polyglot field '" - + resolvedPolyglotField.qualifiedName() - + "'"; - case ResolvedPolyglotSymbol resolvedPolyglotSymbol -> "Polyglot symbol '" - + resolvedPolyglotSymbol.qualifiedName() - + "'"; + case ResolvedPolyglotField resolvedPolyglotField -> + "Polyglot field '" + resolvedPolyglotField.qualifiedName() + "'"; + case ResolvedPolyglotSymbol resolvedPolyglotSymbol -> + "Polyglot symbol '" + resolvedPolyglotSymbol.qualifiedName() + "'"; default -> throw new UnsupportedOperationException("unimplemented: " + resolvedName); }; } diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/pass/lint/unusedimports/UsedSymbolsCollectorTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/pass/lint/unusedimports/UsedSymbolsCollectorTest.java index b30064a0a7c9..acd2509cfd48 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/pass/lint/unusedimports/UsedSymbolsCollectorTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/pass/lint/unusedimports/UsedSymbolsCollectorTest.java @@ -24,8 +24,8 @@ public void collectUsedSymbols_FromSimpleExpression() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -43,8 +43,8 @@ public void collectUsedSymbols_FromNestedExpression() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -66,9 +66,9 @@ public void unusedSymbols_1() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -85,9 +85,9 @@ public void unusedSymbols_2() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -104,9 +104,9 @@ public void inlineSignature_Parameter() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -121,9 +121,10 @@ public void inlineSignature_Parameter() { @Test public void inlineSignature_ReturnType() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type A - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type A + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -138,9 +139,10 @@ public void inlineSignature_ReturnType() { @Test public void typeAscription_ReturnType() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -158,9 +160,9 @@ public void typeAscription_ThrownError() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - type Error - """); + type T + type Error + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -178,11 +180,11 @@ public void typeAscription_TypeSet() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type A - type B - type C - type D - """); + type A + type B + type C + type D + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -206,9 +208,9 @@ public void typeAscription_PartiallyAppliedMethod() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type S - type T - """); + type S + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -228,9 +230,10 @@ public void typeAscription_PartiallyAppliedMethod() { @Test public void typeCast_NestedMethodBody() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -248,9 +251,10 @@ public void typeCast_NestedMethodBody() { @Test public void annotation_1() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -268,8 +272,8 @@ public void method_1() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - method x = x + 1 - """); + method x = x + 1 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -286,9 +290,9 @@ public void method_2() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - method self = 42 - """); + type T + method self = 42 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -305,9 +309,9 @@ public void caseBranch_1() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons - """); + type T + Cons + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -326,9 +330,9 @@ public void caseBranch_2() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons - """); + type T + Cons + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -347,13 +351,13 @@ public void constructors() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Boolean"), """ - export project.Boolean.Boolean.False - export project.Boolean.Boolean.True + export project.Boolean.Boolean.False + export project.Boolean.Boolean.True - type Boolean - False - True - """); + type Boolean + False + True + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -375,11 +379,11 @@ public void constructorInPattern() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type A - type B - Value data - type C - """); + type A + type B + Value data + type C + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -398,9 +402,9 @@ public void noUsedSymbol_ForUnrelatedImport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -422,13 +426,13 @@ public void reexport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Other_Module"), """ - type My_Type - """); + type My_Type + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - export project.Other_Module.My_Type - """); + export project.Other_Module.My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -445,13 +449,13 @@ public void reexport_Rename() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Other_Module"), """ - type Other_Type - """); + type Other_Type + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - export project.Other_Module.Other_Type as My_Type - """); + export project.Other_Module.Other_Type as My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -468,14 +472,14 @@ public void reexport_Case_Branch_TypeConstructor() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Other_Module"), """ - type X - Cons - """); + type X + Cons + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - export project.Other_Module.X as T - """); + export project.Other_Module.X as T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -492,15 +496,16 @@ public void reexport_Case_Branch_TypeConstructor() { @Test public void extensionMethod_ImportAll_DoesNotWork() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Extensions"), """ - import project.Module.T - T.extension_method = 42 - """); + import project.Module.T + T.extension_method = 42 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -518,15 +523,16 @@ public void extensionMethod_ImportAll_DoesNotWork() { @Test public void usedSymbol_FromSyntheticSubmodule() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.A.B"), """ - type B_Type - """); + QualifiedName.fromString("local.Proj.A.B"), + """ + type B_Type + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.A"), """ - export project.A.B - type A_Type - """); + export project.A.B + type A_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -544,13 +550,13 @@ public void usedExtensionMethod_FromModule_InsideSyntheticModule() { compilerCtx.createModule( QualifiedName.fromString("local.Lib.A.A"), """ - static_method x = x - """); + static_method x = x + """); compilerCtx.createModule( QualifiedName.fromString("local.Lib.Main"), """ - export project.A.A - """); + export project.A.A + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/BindingsMapTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/BindingsMapTest.java index a00a2473e985..f1e0e338c11b 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/BindingsMapTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/BindingsMapTest.java @@ -26,13 +26,13 @@ public void foo() { compilerCtx.createModule( QualifiedName.fromString("local.Lib.A.A"), """ - static_method x = x - """); + static_method x = x + """); compilerCtx.createModule( QualifiedName.fromString("local.Lib.Main"), """ - export project.A.A - """); + export project.A.A + """); var projMainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/CompilerErrorTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/CompilerErrorTest.java index a1b4a8d3bfa4..095a91a2ec34 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/CompilerErrorTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/CompilerErrorTest.java @@ -19,11 +19,12 @@ public final class CompilerErrorTest { @Test public void variablesIsRedefinedInIfBranch() { var modName = QualifiedName.fromString("local.Proj.Check"); - var code = """ - check x = - x = 'No' - x == 'False' - """; + var code = + """ + check x = + x = 'No' + x == 'False' + """; var m = compilerCtx.createModule(modName, code); try { var res = compilerCtx.getCompiler().run(m); diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/MultipleProjectsTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/MultipleProjectsTest.java index c5ba5604966d..5d15ace0f41a 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/MultipleProjectsTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/MultipleProjectsTest.java @@ -48,13 +48,13 @@ public void canImportType_FromTwoDifferentProjects() { compilerCtx.createModule( QualifiedName.fromString("local.Lib1.Main"), """ - type Lib1_Type - """); + type Lib1_Type + """); compilerCtx.createModule( QualifiedName.fromString("local.Lib2.Main"), """ - type Lib2_Type - """); + type Lib2_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/SyntheticModulesTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/SyntheticModulesTest.java index 1c3fedc39366..95664cffd8c8 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/SyntheticModulesTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/SyntheticModulesTest.java @@ -17,9 +17,10 @@ public class SyntheticModulesTest { @Test public void testCompilationOfSyntheticModules() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.A.B"), """ - type B_Type - """); + QualifiedName.fromString("local.Proj.A.B"), + """ + type B_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), diff --git a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/UnusedImportsTest.java b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/UnusedImportsTest.java index b31ca7a8c6eb..54ecaec482e1 100644 --- a/engine/runtime-compiler/src/test/java/org/enso/compiler/test/UnusedImportsTest.java +++ b/engine/runtime-compiler/src/test/java/org/enso/compiler/test/UnusedImportsTest.java @@ -34,9 +34,9 @@ public void canResolveSimpleImport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), """ - import project.Module.My_Type - main = My_Type - """); + import project.Module.My_Type + main = My_Type + """); compilerCtx.getCompiler().run(mainMod); var modIr = mainMod.getIr(); var bm = getBindingsMap(modIr); @@ -68,9 +68,9 @@ public void unusedImport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -90,9 +90,9 @@ public void unusedSymbols_1() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -110,9 +110,9 @@ public void unusedSymbols_2() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -130,9 +130,9 @@ public void unusedSymbols_InlineSignature_Parameter() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -148,9 +148,10 @@ public void unusedSymbols_InlineSignature_Parameter() { @Test public void unusedSymbols_InlineSignature_ReturnType() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type A - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type A + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -167,9 +168,9 @@ public void unusedSymbols_InlineSignature_TypeCast() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type_1 - type My_Type_2 - """); + type My_Type_1 + type My_Type_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -187,9 +188,10 @@ public void unusedSymbols_InlineSignature_TypeCast() { @Test public void unusedSymbols_InTypeAscription_ReturnType() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -207,9 +209,9 @@ public void unusedSymbols_InTypeAscription_ThrownError() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - type Error - """); + type T + type Error + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -227,10 +229,10 @@ public void unusedSymbols_InTypeAscription_MultipleThrownErrors() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - type Error_1 - type Error_2 - """); + type T + type Error_1 + type Error_2 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -248,11 +250,11 @@ public void unusedSymbols_InTypeAscription_Complicated() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type A - type B - type C - type D - """); + type A + type B + type C + type D + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -270,9 +272,9 @@ public void unusedSymbols_InTypeAscription_PartiallyAppliedMethod() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type S - type T - """); + type S + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -293,9 +295,10 @@ public void unusedSymbols_InTypeAscription_PartiallyAppliedMethod() { @Test public void unusedSymbols_ExtensionMethod() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -310,9 +313,10 @@ public void unusedSymbols_ExtensionMethod() { @Test public void unusedSymbols_ExtensionMethod_OnModule() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -329,9 +333,9 @@ public void unusedSymbols_ConversionMethod() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - type U - """); + type T + type U + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -348,13 +352,13 @@ public void noWarning_WhenImportingSymbolFromReexport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Other_Module"), """ - type My_Type - """); + type My_Type + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - export project.Other_Module.My_Type - """); + export project.Other_Module.My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -371,8 +375,8 @@ public void noWarningWhenSymbolIsUsedInExport_SimpleExport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -389,8 +393,8 @@ public void noWarningWhenSymbolIsUsedInExport_RenameExport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -407,8 +411,8 @@ public void noWarningWhenSymbolIsUsedInExport_OnlyNamesExport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -425,8 +429,8 @@ public void ignoresDuplicatedImports() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type My_Type - """); + type My_Type + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -446,13 +450,13 @@ public void importConstructors() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Boolean"), """ - export project.Boolean.Boolean.False - export project.Boolean.Boolean.True + export project.Boolean.Boolean.False + export project.Boolean.Boolean.True - type Boolean - False - True - """); + type Boolean + False + True + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -469,8 +473,8 @@ public void canDetectUnusedMethods() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - method x = x + 1 - """); + method x = x + 1 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -487,9 +491,9 @@ public void typeOnMethodIsUsed() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - method self = 42 - """); + type T + method self = 42 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -520,10 +524,10 @@ public void importAll_IsIgnored() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type A - type B - A.extension_method self = 42 - """); + type A + type B + A.extension_method self = 42 + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -538,9 +542,10 @@ public void importAll_IsIgnored() { @Test public void usedSymbol_InCaseBranch_TypePattern() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -559,9 +564,9 @@ public void usedSymbol_InCaseBranch_Constructor() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons - """); + type T + Cons + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -580,9 +585,9 @@ public void usedSymbol_InCaseBranch_TypeConstructor() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons - """); + type T + Cons + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -601,11 +606,11 @@ public void usedSymbol_InCaseBranch_TypeConstructor_WithFields() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons data - type S - Value data - """); + type T + Cons data + type S + Value data + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -625,10 +630,10 @@ public void usedSymbol_InCaseBranch_TypeConstructor_OtherUsages_1() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons data - type S - """); + type T + Cons data + type S + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -648,11 +653,11 @@ public void usedSymbol_InCaseBranch_TypeConstructor_OtherUsages_2() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons data - type S - type U - """); + type T + Cons data + type S + type U + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -672,14 +677,14 @@ public void usedSymbol_InCaseBranch_TypeConstructor_Reexport() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Other_Module"), """ - type X - Cons - """); + type X + Cons + """); compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - export project.Other_Module.X as T - """); + export project.Other_Module.X as T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -696,9 +701,10 @@ public void usedSymbol_InCaseBranch_TypeConstructor_Reexport() { @Test public void usedSymbol_InAnnotation_MethodCall() { compilerCtx.createModule( - QualifiedName.fromString("local.Proj.Module"), """ - type T - """); + QualifiedName.fromString("local.Proj.Module"), + """ + type T + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -716,9 +722,9 @@ public void usedSymbol_InAnnotation_Expression() { compilerCtx.createModule( QualifiedName.fromString("local.Proj.Module"), """ - type T - Cons - """); + type T + Cons + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), @@ -739,13 +745,13 @@ public void usedExtensionMethodSymbol_FromModule_InsideSyntheticModule() { compilerCtx.createModule( QualifiedName.fromString("local.Lib.A.A"), """ - static_method x = x - """); + static_method x = x + """); compilerCtx.createModule( QualifiedName.fromString("local.Lib.Main"), """ - export project.A.A - """); + export project.A.A + """); var mainMod = compilerCtx.createModule( QualifiedName.fromString("local.Proj.Main"), diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/common/test/ContextInsightSetupTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/common/test/ContextInsightSetupTest.java index 77d899d26a22..b4e6c5d830c2 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/common/test/ContextInsightSetupTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/common/test/ContextInsightSetupTest.java @@ -36,8 +36,8 @@ public void initializeInsightViaProperty() throws Exception { try (java.io.FileWriter w = new FileWriter(insight)) { w.write( """ - print("Insight started. Properties: " + Object.getOwnPropertyNames(insight).sort()); - """); + print("Insight started. Properties: " + Object.getOwnPropertyNames(insight).sort()); + """); } System.setProperty("enso.dev.insight", insight.getPath()); @@ -47,9 +47,12 @@ public void initializeInsightViaProperty() throws Exception { // triggered. try (var ctx = ContextFactory.create().out(out).build()) { - var fourtyTwo = evalModule(ctx, """ - main = 42 - """); + var fourtyTwo = + evalModule( + ctx, + """ + main = 42 + """); assertEquals("42", fourtyTwo.toString()); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/dump/test/ApiModificationTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/dump/test/ApiModificationTest.java index 579205beaba8..9875a5a48298 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/dump/test/ApiModificationTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/dump/test/ApiModificationTest.java @@ -17,11 +17,13 @@ public final class ApiModificationTest { @Test public void reorderingMethods_DoesNotModifyApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ method_1 = 1 method_2 = 2 """; - var newSrc = """ + var newSrc = + """ method_2 = 2 method_1 = 1 """; @@ -36,11 +38,13 @@ public void reorderingMethods_DoesNotModifyApi() throws IOException { @Test public void reorderingTypes_DoesNotModifyApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ type Type_1 type Type_2 """; - var newSrc = """ + var newSrc = + """ type Type_2 type Type_1 """; @@ -55,11 +59,13 @@ public void reorderingTypes_DoesNotModifyApi() throws IOException { @Test public void reorderingTypeAndMethod_DoesNotModifyApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ type Type method = 1 """; - var newSrc = """ + var newSrc = + """ method = 1 type Type """; @@ -98,12 +104,14 @@ public void reorderingMethodsInType_DoesNotModifyApi() throws IOException { @Test public void reorderingConstructorsInType_DoesNotModifyApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ type Type Cons_2 Cons_1 """; - var newSrc = """ + var newSrc = + """ type Type Cons_1 Cons_2 @@ -121,10 +129,12 @@ public void reorderingConstructorsInType_DoesNotModifyApi() throws IOException { @Test public void addingMethod_ModifiesApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ method_1 = 1 """; - var newSrc = """ + var newSrc = + """ method_1 = 1 method_2 = 2 """; @@ -141,10 +151,12 @@ public void addingMethod_ModifiesApi() throws IOException { @Test public void renamingMethod_ModifiesApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ method = 1 """; - var newSrc = """ + var newSrc = + """ renamed_method = 2 """; compareSignatures( @@ -157,11 +169,13 @@ public void renamingMethod_ModifiesApi() throws IOException { @Test public void removingMethod_ModifiesApi() throws IOException { - var prevSrc = """ + var prevSrc = + """ method_1 = 1 method_2 = 2 """; - var newSrc = """ + var newSrc = + """ method_2 = 2 """; compareSignatures( diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/AnnotationsCompilerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/AnnotationsCompilerTest.java index c115fae8320a..7382446bd08b 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/AnnotationsCompilerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/AnnotationsCompilerTest.java @@ -13,11 +13,13 @@ public class AnnotationsCompilerTest extends CompilerTests { @Test public void testModuleMethod() throws Exception { - var ir = parse(""" - @a expr - @b (x y) - foo a b = a b - """); + var ir = + parse( + """ + @a expr + @b (x y) + foo a b = a b + """); var annotation1 = (Name.Annotation) ir.bindings().apply(0); var annotation2 = (Name.Annotation) ir.bindings().apply(1); @@ -28,11 +30,13 @@ public void testModuleMethod() throws Exception { @Test public void testExtensionMethod() throws Exception { - var ir = parse(""" - @a expr - @b (x y) - Foo.foo a b = a b - """); + var ir = + parse( + """ + @a expr + @b (x y) + Foo.foo a b = a b + """); var annotation1 = (Name.Annotation) ir.bindings().apply(0); var annotation2 = (Name.Annotation) ir.bindings().apply(1); @@ -43,12 +47,14 @@ public void testExtensionMethod() throws Exception { @Test public void testTypeMethod() throws Exception { - var ir = parse(""" - type Foo - @a foo - @b bar - method a b = a b - """); + var ir = + parse( + """ + type Foo + @a foo + @b bar + method a b = a b + """); var typeDefinition = (Definition.SugaredType) ir.bindings().apply(0); @@ -63,12 +69,14 @@ public void testTypeMethod() throws Exception { @Test public void testConstructor() throws Exception { - var ir = parse(""" - type Foo - @a foo - @b bar - Cons a b - """); + var ir = + parse( + """ + type Foo + @a foo + @b bar + Cons a b + """); var typeDefinition = (Definition.SugaredType) ir.bindings().apply(0); @@ -83,10 +91,12 @@ public void testConstructor() throws Exception { @Test public void testInvalidComplexType() throws Exception { - var ir = parse(""" - type Foo - bar a = - """); + var ir = + parse( + """ + type Foo + bar a = + """); var typeDefinition = (Definition.SugaredType) ir.bindings().apply(0); var methodOrError = typeDefinition.body().apply(0); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/BindingsMapResolutionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/BindingsMapResolutionTest.java index 6385ab4d0ff9..23556690e61c 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/BindingsMapResolutionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/BindingsMapResolutionTest.java @@ -83,9 +83,11 @@ public void resolveQualifiedName_FromSingleImport_TwoProjects() throws IOExcepti @Test public void resolveQualifiedName_DefinedEntity() throws IOException { - var projDir = createProject(""" - type My_Type - """); + var projDir = + createProject( + """ + type My_Type + """); testBindingsMap( projDir, bindingsMap -> { @@ -97,10 +99,12 @@ public void resolveQualifiedName_DefinedEntity() throws IOException { @Test @Ignore public void resolveConstructor_DefinedEntity() throws IOException { - var projDir = createProject(""" - type My_Type - Cons - """); + var projDir = + createProject( + """ + type My_Type + Cons + """); testBindingsMap( projDir, bindingsMap -> { @@ -199,15 +203,15 @@ public void resolveExportedType() throws IOException { new SourceModule( QualifiedName.fromString("My_Module"), """ - type My_Type - Cons - """), + type My_Type + Cons + """), new SourceModule( QualifiedName.fromString("Main"), """ - import project.My_Module.My_Type - export project.My_Module.My_Type - """)), + import project.My_Module.My_Type + export project.My_Module.My_Type + """)), projDir); testBindingsMap( projDir, @@ -230,20 +234,22 @@ public void resolveReexportedType() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - import project.My_Module.My_Type - export project.My_Module.My_Type - """), + import project.My_Module.My_Type + export project.My_Module.My_Type + """), new SourceModule( QualifiedName.fromString("My_Module"), """ - type My_Type - Cons - """)), + type My_Type + Cons + """)), libDir); ProjectUtils.createProject( - "Proj", """ - from local.Lib import all - """, projDir); + "Proj", + """ + from local.Lib import all + """, + projDir); testBindingsMap( projDir, bindingsMap -> { @@ -263,13 +269,13 @@ public void notResolveModule_IfItItWasNotDirectlyImported() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - import project.My_Module.My_Type - """), + import project.My_Module.My_Type + """), new SourceModule( QualifiedName.fromString("My_Module"), """ - type My_Type - """)), + type My_Type + """)), projDir); testBindingsMap( projDir, @@ -292,26 +298,28 @@ public void resolveReexportedType_MoreDefinedEntitiesInLib() throws IOException new SourceModule( QualifiedName.fromString("Main"), """ - import project.My_Other_Module.My_Other_Type - import project.My_Module.My_Type - export project.My_Other_Module.My_Other_Type - export project.My_Module.My_Type - """), + import project.My_Other_Module.My_Other_Type + import project.My_Module.My_Type + export project.My_Other_Module.My_Other_Type + export project.My_Module.My_Type + """), new SourceModule( QualifiedName.fromString("My_Module"), """ - type My_Type - """), + type My_Type + """), new SourceModule( QualifiedName.fromString("My_Other_Module"), """ - type My_Other_Type - """)), + type My_Other_Type + """)), libDir); ProjectUtils.createProject( - "Proj", """ - from local.Lib import all - """, projDir); + "Proj", + """ + from local.Lib import all + """, + projDir); testBindingsMap( projDir, bindingsMap -> { @@ -338,27 +346,29 @@ public void resolveReexportedType_FromDifferentProject() throws IOException { new SourceModule( QualifiedName.fromString("Other_Module"), """ - type Other_Type - """), + type Other_Type + """), new SourceModule( QualifiedName.fromString("Main"), """ - import project.Other_Module.Other_Type - export project.Other_Module.Other_Type - """)), + import project.Other_Module.Other_Type + export project.Other_Module.Other_Type + """)), otherLibDir); ProjectUtils.createProject( "Lib", """ - import local.Other_Lib.Other_Module.Other_Type - export local.Other_Lib.Other_Module.Other_Type - type My_Type - """, + import local.Other_Lib.Other_Module.Other_Type + export local.Other_Lib.Other_Module.Other_Type + type My_Type + """, libDir); ProjectUtils.createProject( - "Proj", """ - from local.Lib import all - """, projDir); + "Proj", + """ + from local.Lib import all + """, + projDir); testBindingsMap( projDir, bindingsMap -> { @@ -379,31 +389,33 @@ public void resolveReexportedType_ThreeProjects() throws IOException { projDir.toFile().mkdir(); otherLibDir.toFile().mkdir(); ProjectUtils.createProject( - "Other_Lib", """ - type Other_Type - """, otherLibDir); + "Other_Lib", + """ + type Other_Type + """, + otherLibDir); ProjectUtils.createProject( "Lib", Set.of( new SourceModule( QualifiedName.fromString("Main"), """ - import project.My_Module.My_Type - export project.My_Module.My_Type - """), + import project.My_Module.My_Type + export project.My_Module.My_Type + """), new SourceModule( QualifiedName.fromString("My_Module"), """ - type My_Type - Cons - """)), + type My_Type + Cons + """)), libDir); ProjectUtils.createProject( "Proj", """ - from local.Other_Lib import all - from local.Lib import all - """, + from local.Other_Lib import all + from local.Lib import all + """, projDir); testBindingsMap( projDir, @@ -436,13 +448,13 @@ public void resolveModule_InImportCycle_1() throws IOException { new SourceModule( QualifiedName.fromString("Data.A"), """ - import project.Data.B - """), + import project.Data.B + """), new SourceModule( QualifiedName.fromString("Data.B"), """ - import project.Data.A - """), + import project.Data.A + """), new SourceModule(QualifiedName.fromString("Main"), "")), projDir); testBindingsMap( @@ -466,13 +478,13 @@ public void resolveModule_InImportCycle_2() throws IOException { new SourceModule( QualifiedName.fromString("A"), """ - import project.B - """), + import project.B + """), new SourceModule( QualifiedName.fromString("B"), """ - import project.A - """), + import project.A + """), new SourceModule(QualifiedName.fromString("Main"), "")), projDir); testBindingsMap( @@ -496,19 +508,19 @@ public void resolveModule_InImportCycle_3() throws IOException { new SourceModule( QualifiedName.fromString("A"), """ - import project.B - import project.C - """), + import project.B + import project.C + """), new SourceModule( QualifiedName.fromString("B"), """ - import project.A - """), + import project.A + """), new SourceModule( QualifiedName.fromString("C"), """ - type C_Type - """), + type C_Type + """), new SourceModule(QualifiedName.fromString("Main"), "")), projDir); testBindingsMap( @@ -530,9 +542,11 @@ public void noStackOverflow_WhenResolving_StandardBoolean() throws IOException { var projDir = tmpDir.toPath().resolve("Proj"); projDir.toFile().mkdir(); ProjectUtils.createProject( - "Proj", """ - import Standard.Base.Any - """, projDir); + "Proj", + """ + import Standard.Base.Any + """, + projDir); testBindingsMap( projDir, bindingsMap -> { @@ -555,8 +569,8 @@ public void resolveMainModule_FromDifferentProject() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - # Empty on purpose - """)), + # Empty on purpose + """)), libDir); ProjectUtils.createProject( "Proj", @@ -564,8 +578,8 @@ public void resolveMainModule_FromDifferentProject() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - from local.Lib import all - """)), + from local.Lib import all + """)), projDir); testBindingsMap( projDir, @@ -584,9 +598,9 @@ private Path createProject(String mainModuleSrc) throws IOException { new SourceModule( QualifiedName.fromString("My_Vector"), """ - type My_Vector - Cons data - """)); + type My_Vector + Cons data + """)); ProjectUtils.createProject("Proj", modules, projDir); return projDir; } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ErrorCompilerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ErrorCompilerTest.java index d60f8d5efcc8..f564f94a17d6 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ErrorCompilerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ErrorCompilerTest.java @@ -16,9 +16,11 @@ public class ErrorCompilerTest extends CompilerTests { @Test public void unfinishedLiteral1() throws Exception { - var ir = parse(""" - foo = "unfinished literal... - """); + var ir = + parse( + """ + foo = "unfinished literal... + """); assertSingleSyntaxError( ir, Syntax.UnclosedTextLiteral$.MODULE$, "Unclosed text literal", 6, 28); @@ -26,10 +28,12 @@ public void unfinishedLiteral1() throws Exception { @Test public void brokenAnnotationMissingArgument() throws Exception { - var ir = parse(""" - @anno - fn = 10 - """); + var ir = + parse( + """ + @anno + fn = 10 + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 0, 5); @@ -37,20 +41,24 @@ public void brokenAnnotationMissingArgument() throws Exception { @Test public void dotUnderscore() throws Exception { - var ir = parse(""" - run op = - op._ - """); + var ir = + parse( + """ + run op = + op._ + """); assertSingleSyntaxError(ir, Syntax.InvalidUnderscore$.MODULE$, "Invalid use of _", 14, 15); } @Test public void spaceDotUnderscore() throws Exception { - var ir = parse(""" - run op = - op ._ - """); + var ir = + parse( + """ + run op = + op ._ + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 14, 16); @@ -58,37 +66,45 @@ public void spaceDotUnderscore() throws Exception { @Test public void dotUnderscore2() throws Exception { - var ir = parse(""" - run op = - op._.something - """); + var ir = + parse( + """ + run op = + op._.something + """); assertSingleSyntaxError(ir, Syntax.InvalidUnderscore$.MODULE$, "Invalid use of _", 14, 15); } @Test public void unfinishedLiteral2() throws Exception { - var ir = parse(""" - foo = 'unfinished literal... - """); + var ir = + parse( + """ + foo = 'unfinished literal... + """); assertSingleSyntaxError( ir, Syntax.UnclosedTextLiteral$.MODULE$, "Unclosed text literal", 6, 28); } @Test public void unpairedLiteral1() throws Exception { - var ir = parse(""" - foo = "unpaired literal' - """); + var ir = + parse( + """ + foo = "unpaired literal' + """); assertSingleSyntaxError( ir, Syntax.UnclosedTextLiteral$.MODULE$, "Unclosed text literal", 6, 24); } @Test public void unpairedLiteral2() throws Exception { - var ir = parse(""" - foo = 'unpaired literal" - """); + var ir = + parse( + """ + foo = 'unpaired literal" + """); assertSingleSyntaxError( ir, Syntax.UnclosedTextLiteral$.MODULE$, "Unclosed text literal", 6, 24); } @@ -113,61 +129,73 @@ public void incompleteTypeDefinition() throws Exception { @Test public void lessThanTwoArgumentsToAnOperator() throws Exception { - var ir = parse(""" - type T - %& self = 0 - """); + var ir = + parse( + """ + type T + %& self = 0 + """); assertSingleSyntaxError( ir, Syntax.InvalidOperator$.MODULE$, "Operator must have two arguments", 10, 21); } @Test public void moreThanTwoArgumentsToAnOperator() throws Exception { - var ir = parse(""" - type X - &% self one two = one+two - """); + var ir = + parse( + """ + type X + &% self one two = one+two + """); assertSingleSyntaxError( ir, Syntax.InvalidOperator$.MODULE$, "Operator must have two arguments", 10, 35); } @Test public void badCase1() throws Exception { - var ir = parse(""" - foo = case x of - 4 - """); + var ir = + parse( + """ + foo = case x of + 4 + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Invalid case expression"), null, 6, 18); } @Test public void badCase2() throws Exception { - var ir = parse(""" - foo = case x of - 4 -> - """); + var ir = + parse( + """ + foo = case x of + 4 -> + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Invalid case expression"), null, 6, 21); } @Test public void badCase3() throws Exception { - var ir = parse(""" - foo = case x of - 4-> - """); + var ir = + parse( + """ + foo = case x of + 4-> + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Invalid case expression"), null, 6, 20); } @Test public void badCase4() throws Exception { - var ir = parse(""" - main = - case value of - -1 ->"minus one" - """); + var ir = + parse( + """ + main = + case value of + -1 ->"minus one" + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Operator must be applied to two operands"), null, 32, 45); } @@ -341,9 +369,9 @@ public void malformedTypeException() throws Exception { var ir = parse( """ - fan_out_to_columns : Table -> Text | Integer -> (Any -> Vector Any) -> | Nothing -> Problem_Behavior -> Table | Nothing - fan_out_to_columns table text_or_integer any_to_vector_any wat problem_behavior = Nothing - """); + fan_out_to_columns : Table -> Text | Integer -> (Any -> Vector Any) -> | Nothing -> Problem_Behavior -> Table | Nothing + fan_out_to_columns table text_or_integer any_to_vector_any wat problem_behavior = Nothing + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 48, 119); } @@ -504,10 +532,12 @@ public void illegalPrivateVariableDeclaration() throws Exception { @Test public void illegalPrivateKeywordUseInType() throws Exception { - var ir = parse(""" - type T - private - """); + var ir = + parse( + """ + type T + private + """); assertSingleSyntaxError( ir, Syntax.UnexpectedDeclarationInType$.MODULE$, @@ -518,20 +548,24 @@ public void illegalPrivateKeywordUseInType() throws Exception { @Test public void illegalPrivateKeywordRepeatedDeclarations() throws Exception { - var ir = parse(""" - private - private - """); + var ir = + parse( + """ + private + private + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 8, 15); } @Test public void illegalPrivateKeywordUseInMethodBody() throws Exception { - var ir = parse(""" - method = - private priv_nested_method x = x - """); + var ir = + parse( + """ + method = + private priv_nested_method x = x + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("The \"private\" keyword is not expected in this context"), @@ -542,18 +576,22 @@ public void illegalPrivateKeywordUseInMethodBody() throws Exception { @Test public void illegalPrivateTypeDeclaration() throws Exception { - var ir = parse(""" - private type T - """); + var ir = + parse( + """ + private type T + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 0, 14); } @Test public void illegalEscapeSequence() throws Exception { - var ir = parse(""" - escape = 'wrong \\c sequence' - """); + var ir = + parse( + """ + escape = 'wrong \\c sequence' + """); assertSingleSyntaxError( ir, new Syntax.InvalidEscapeSequence("wrong sequence"), @@ -567,24 +605,26 @@ public void testNPE183814303() throws Exception { var ir = parse( """ - from Standard.Base import all + from Standard.Base import all - main = - x = "foo" - z = x. length - IO.println z - """); + main = + x = "foo" + z = x. length + IO.println z + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 60, 62); } @Test public void testNPE183863754() throws Exception { - var ir = parse(""" - main = - # meh - 42 - """); + var ir = + parse( + """ + main = + # meh + 42 + """); var errors = ir.preorder().filter(Syntax.class::isInstance).map(Syntax.class::cast); assertEquals("One error", 1, errors.size()); assertEquals(Syntax.UnexpectedExpression$.MODULE$, errors.head().reason()); @@ -594,11 +634,13 @@ public void testNPE183863754() throws Exception { @Test public void testMissingEqualsInMethodDefinition() throws Exception { - var ir = parse(""" - type T - method self - 42 - """); + var ir = + parse( + """ + type T + method self + 42 + """); assertSingleSyntaxError( ir, Syntax.UnexpectedDeclarationInType$.MODULE$, @@ -609,28 +651,34 @@ public void testMissingEqualsInMethodDefinition() throws Exception { @Test public void testAnnotation1() throws Exception { - var ir = parse(""" - @x ` - id x = x - """); + var ir = + parse( + """ + @x ` + id x = x + """); assertSingleSyntaxError(ir, new Syntax.UnsupportedSyntax("Unexpected token"), null, 3, 4); } @Test public void testAnnotation2() throws Exception { - var ir = parse(""" - @` foo - id x = x - """); + var ir = + parse( + """ + @` foo + id x = x + """); assertSingleSyntaxError( ir, Syntax.UnexpectedExpression$.MODULE$, "Unexpected expression", 0, 6); } @Test public void testEmptyBody() throws Exception { - var ir = parse(""" - main = - """); + var ir = + parse( + """ + main = + """); var method = (Method) ir.bindings().apply(0); assertTrue(method.body() instanceof Empty); @@ -638,10 +686,12 @@ public void testEmptyBody() throws Exception { @Test public void testBodyWithComment() throws Exception { - var ir = parse(""" - main = - # comment - """); + var ir = + parse( + """ + main = + # comment + """); var method = (Method) ir.bindings().apply(0); var body = (Expression.Block) method.body(); @@ -651,40 +701,48 @@ public void testBodyWithComment() throws Exception { @Test public void exportAllIsNotAllowed() { - var ir = parse(""" - from project.Module export all - """); + var ir = + parse( + """ + from project.Module export all + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("\"all\" not allowed in export statement"), null, 0, 30); } @Test public void exportHidingIsNotAllowed() { - var ir = parse(""" - from project.Module export all hiding Foo - """); + var ir = + parse( + """ + from project.Module export all hiding Foo + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("\"all\" not allowed in export statement"), null, 0, 41); } @Test public void inlineDocCommentIsNotAllowed_1() { - var ir = parse(""" - main args = - v = 42 ## meh - v - """); + var ir = + parse( + """ + main args = + v = 42 ## meh + v + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Unexpected documentation at end of line"), null, 23, 29); } @Test public void inlineDocCommentIsNotAllowed_2() { - var ir = parse(""" - main args = - v = 42 - v ## meh - """); + var ir = + parse( + """ + main args = + v = 42 + v ## meh + """); assertSingleSyntaxError( ir, new Syntax.UnsupportedSyntax("Unexpected documentation at end of line"), null, 29, 35); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecCompilerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecCompilerTest.java index 4de36d88efa4..d39ac6fccede 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecCompilerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecCompilerTest.java @@ -41,11 +41,11 @@ public void testCaseOfWithNegativeConstant() { ctxRule.eval( LanguageInfo.ID, """ - run value = - case value of - -1 -> "minus one" - _ -> "none" - """); + run value = + case value of + -1 -> "minus one" + _ -> "none" + """); var run = module.invokeMember("eval_expression", "run"); var minusOne = run.execute(-1); assertEquals("minus one", minusOne.asString()); @@ -55,10 +55,13 @@ public void testCaseOfWithNegativeConstant() { @Test public void testDesugarOperators() { - var module = ctxRule.eval(LanguageInfo.ID, """ - main = - ma ==ums== - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + main = + ma ==ums== + """); try { var run = module.invokeMember("eval_expression", "main"); fail("Unexpected result: " + run); @@ -69,9 +72,12 @@ public void testDesugarOperators() { @Test public void testDesugarOperatorsLeftRight() { - var module = ctxRule.eval(LanguageInfo.ID, """ - main = (+ (2 *)) - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + main = (+ (2 *)) + """); try { var run = module.invokeMember("eval_expression", "main"); fail("Unexpected result: " + run); @@ -82,9 +88,12 @@ public void testDesugarOperatorsLeftRight() { @Test public void testDesugarOperatorsRightLeft() { - var module = ctxRule.eval(LanguageInfo.ID, """ - main = ((* 2) +) - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + main = ((* 2) +) + """); try { var run = module.invokeMember("eval_expression", "main"); fail("Unexpected result: " + run); @@ -104,12 +113,12 @@ public void testHalfAssignment() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base.Errors.Common import all - run value = - x = 4 - y = - z = 5 - """); + from Standard.Base.Errors.Common import all + run value = + x = 4 + y = + z = 5 + """); var run = module.invokeMember("eval_expression", "run"); try { var never = run.execute(-1); @@ -121,10 +130,13 @@ public void testHalfAssignment() { @Test public void redefinedArgument() { - var module = ctxRule.eval(LanguageInfo.ID, """ - type My_Type - Value a b c a - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + type My_Type + Value a b c a + """); var run = module.invokeMember("eval_expression", "My_Type.Value"); var atom = run.newInstance(1, 2, 3, 4); assertFalse("In spite of error we get an instance back: " + atom, atom.isException()); @@ -143,11 +155,11 @@ public void testSelfAssignment() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base.Errors.Common import all - run value = - meta1 = meta1 - meta1 - """); + from Standard.Base.Errors.Common import all + run value = + meta1 = meta1 + meta1 + """); var run = module.invokeMember("eval_expression", "run"); var error = run.execute(-1); assertTrue("We get an error value back", error.isException()); @@ -161,12 +173,12 @@ public void testRecursiveDefinition() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base import all + from Standard.Base import all - run prefix = - op = if False then 42 else prefix+op - op - """); + run prefix = + op = if False then 42 else prefix+op + op + """); var run = module.invokeMember("eval_expression", "run"); var error = run.execute("Nope: "); assertTrue("We get an error value back", error.isException()); @@ -179,11 +191,12 @@ public void testRecursiveDefinition() { public void testDefault() { var module = ctxRule.eval( - LanguageInfo.ID, """ - f x=1 = x - value_from_default = - f default - """); + LanguageInfo.ID, + """ + f x=1 = x + value_from_default = + f default + """); var result = module.invokeMember("eval_expression", "value_from_default"); assertEquals("Value obtained from default argument", 1, result.asInt()); } @@ -194,21 +207,24 @@ public void testIdentCalledDefault() { ctxRule.eval( LanguageInfo.ID, """ - f x=1 = x - value_from_binding = - default = 2 - f default - """); + f x=1 = x + value_from_binding = + default = 2 + f default + """); var result = module.invokeMember("eval_expression", "value_from_binding"); assertEquals("Value obtained from binding", 2, result.asInt()); } @Test public void dotUnderscore() { - var module = ctxRule.eval(LanguageInfo.ID, """ - run op = - op._ - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + run op = + op._ + """); var run = module.invokeMember("eval_expression", "run"); try { var error = run.execute("false_hope"); @@ -228,13 +244,13 @@ public void chainedSyntax() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base import all + from Standard.Base import all - nums n = [1, 2, 3, 4, 5] - . map (x-> x*2) - . filter (x-> x % 3 == 0) - . take n - """); + nums n = [1, 2, 3, 4, 5] + . map (x-> x*2) + . filter (x-> x % 3 == 0) + . take n + """); var run = module.invokeMember("eval_expression", "nums"); var six = run.execute(1); assertTrue(six.hasArrayElements()); @@ -244,11 +260,14 @@ public void chainedSyntax() { @Test public void chainedSyntaxOperator() { - var module = ctxRule.eval(LanguageInfo.ID, """ - nums n = n - * 2 - % 3 - """); + var module = + ctxRule.eval( + LanguageInfo.ID, + """ + nums n = n + * 2 + % 3 + """); var run = module.invokeMember("eval_expression", "nums"); var result = run.execute(5); assertEquals("10 % 3 is one", 1, result.asInt()); @@ -260,9 +279,9 @@ public void inlineReturnSignature() { ctxRule.eval( LanguageInfo.ID, """ - import Standard.Base.Data.Numbers.Integer - foo (x : Integer) (y : Integer) -> Integer = 10*x + y - """); + import Standard.Base.Data.Numbers.Integer + foo (x : Integer) (y : Integer) -> Integer = 10*x + y + """); var foo = module.invokeMember("eval_expression", "foo"); assertTrue("foo a function", foo.canExecute()); assertEquals(45, foo.execute(4, 5).asInt()); @@ -290,17 +309,17 @@ member_foo self (y : Integer) z -> Integer = 100*z + 10*y + self.x public void inlineWithBlanks() { var code = """ - remap rows:Map -> Map = - rows.map (_.set_u 5) + remap rows:Map -> Map = + rows.map (_.set_u 5) - type Map - M v u=3 + type Map + M v u=3 - map self fn = Map.M (fn self) - set_u self i = Map.M self.v i + map self fn = Map.M (fn self) + set_u self i = Map.M self.v i - run n = remap (Map.M n) - """; + run n = remap (Map.M n) + """; var module = ctxRule.eval(LanguageInfo.ID, code); var run = module.invokeMember("eval_expression", "run"); assertTrue("run is a function", run.canExecute()); @@ -313,13 +332,13 @@ public void inlineReturnSignatureOnLocalFunction() { ctxRule.eval( LanguageInfo.ID, """ - import Standard.Base.Data.Numbers.Integer - foo x y = - inner_foo (z : Integer) -> Integer = 100*z + 10*y + x - a = 3 - r = inner_foo a - r + 50000 - """); + import Standard.Base.Data.Numbers.Integer + foo x y = + inner_foo (z : Integer) -> Integer = 100*z + 10*y + x + a = 3 + r = inner_foo a + r + 50000 + """); var instance = module.invokeMember("eval_expression", "foo"); var result = instance.execute(1, 2); assertEquals(50321, result.asInt()); @@ -331,9 +350,9 @@ public void inlineReturnSignatureWithoutArguments() { ctxRule.eval( LanguageInfo.ID, """ - import Standard.Base.Data.Numbers.Integer - the_number -> Integer = 23 - """); + import Standard.Base.Data.Numbers.Integer + the_number -> Integer = 23 + """); var result = module.invokeMember("eval_expression", "the_number"); assertEquals("Function-return syntax can be used with 0 arguments", 23, result.asInt()); } @@ -351,9 +370,9 @@ public void weirdReturnTypeSignature1() throws Exception { Source.newBuilder( LanguageInfo.ID, """ - from Standard.Base import Integer - foo a:Integer -> Integer = a+10 - """, + from Standard.Base import Integer + foo a:Integer -> Integer = a+10 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -370,9 +389,9 @@ public void weirdReturnTypeSignature2() throws Exception { Source.newBuilder( LanguageInfo.ID, """ - from Standard.Base import Integer - foo a : Integer -> Integer = a+10 - """, + from Standard.Base import Integer + foo a : Integer -> Integer = a+10 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -392,12 +411,12 @@ public void testInvalidEnsoProjectRef() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base.Errors.Common import all - from Standard.Base.Meta.Enso_Project import enso_project - run dummy = - _ = dummy - (enso_project.data / "foo").to_display_text - """); + from Standard.Base.Errors.Common import all + from Standard.Base.Meta.Enso_Project import enso_project + run dummy = + _ = dummy + (enso_project.data / "foo").to_display_text + """); var run = module.invokeMember("eval_expression", "run"); var err = run.execute(0); assertEquals("Error: Module is not a part of a package.", err.asString()); @@ -409,12 +428,12 @@ public void testDoubledRandom() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base import all - polyglot java import java.util.Random + from Standard.Base import all + polyglot java import java.util.Random - run seed = - Random.new_generator seed - """); + run seed = + Random.new_generator seed + """); var run = module.invokeMember("eval_expression", "run"); try { var err = run.execute(1L); @@ -431,13 +450,13 @@ public void testUnknownStaticField() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base import all - polyglot java import java.util.Random as R + from Standard.Base import all + polyglot java import java.util.Random as R - run seed = case seed of - R.NO_FIELD -> 0 - _ -> -1 - """); + run seed = case seed of + R.NO_FIELD -> 0 + _ -> -1 + """); var run = module.invokeMember("eval_expression", "run"); try { var err = run.execute(1L); @@ -451,16 +470,16 @@ public void testUnknownStaticField() { public void testFnAsADefaultValue() { var code = """ - type N - type T - V (r:(T -> N | T)=(_->N)) + type N + type T + V (r:(T -> N | T)=(_->N)) - v self = self.r self + v self = self.r self - run type = case type of - 0 -> T.V - 1 -> T.V (_->N) - """; + run type = case type of + 0 -> T.V + 1 -> T.V (_->N) + """; var module = ctxRule.eval(LanguageInfo.ID, code); var run = module.invokeMember("eval_expression", "run"); var real = run.execute(1L); @@ -474,15 +493,15 @@ public void testFnAsADefaultValue() { public void testTemporaryFileSpecProblem() { var code = """ - from Standard.Base.Errors.Common import all + from Standard.Base.Errors.Common import all - run t = F.app f-> - f.read t + run t = F.app f-> + f.read t - type F - read self r = r - app fn = fn F - """; + type F + read self r = r + app fn = fn F + """; var module = ctxRule.eval(LanguageInfo.ID, code); var run = module.invokeMember("eval_expression", "run"); var real = run.execute(1L); @@ -495,12 +514,12 @@ public void testPropertlyIdentifyNameOfJavaClassInError() { ctxRule.eval( LanguageInfo.ID, """ - from Standard.Base.Errors.Common import all - polyglot java import java.lang.Runnable + from Standard.Base.Errors.Common import all + polyglot java import java.lang.Runnable - run value = - Runnable.invoke value - """); + run value = + Runnable.invoke value + """); var run = module.invokeMember(MethodNames.Module.EVAL_EXPRESSION, "run"); try { var never = run.execute(-1); @@ -518,13 +537,13 @@ public void illegalPrivateConversion() { ctxRule.eval( LanguageInfo.ID, """ - type My_Type - type Other_Type - private My_Type.from (other:Other_Type) = - 42 - run value = - 42 - """); + type My_Type + type Other_Type + private My_Type.from (other:Other_Type) = + 42 + run value = + 42 + """); var expectedErrMsg = DeclaredAsPrivate$.MODULE$.explain(); var runMethod = module.invokeMember(Module.EVAL_EXPRESSION, "run"); runMethod.execute(0); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecStrictCompilerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecStrictCompilerTest.java index c9819e38fb82..6d1c0ff33a46 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecStrictCompilerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExecStrictCompilerTest.java @@ -36,10 +36,13 @@ public void cleanMessages() { @Test public void redefinedArgument() { try { - var module = ctxRule.eval("enso", """ - type My_Type - Value a b c a - """); + var module = + ctxRule.eval( + "enso", + """ + type My_Type + Value a b c a + """); fail("Expecting no returned value: " + module); } catch (PolyglotException ex) { assertTrue("Syntax error", ex.isSyntaxError()); @@ -92,11 +95,12 @@ public void testUnknownConstructorLocation() throws Exception { @Test public void testUnknownTypeExtensionMethod() throws Exception { - var code = """ - Unknown_Type.foo = 42 + var code = + """ + Unknown_Type.foo = 42 - main = 42 - """; + main = 42 + """; var src = Source.newBuilder("enso", code, "extension.enso").build(); try { var module = ctxRule.eval(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportCycleDetectionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportCycleDetectionTest.java index 0d6229b336ad..62bcd070591c 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportCycleDetectionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportCycleDetectionTest.java @@ -31,23 +31,23 @@ public void detectCycleInTwoModules() throws IOException { new SourceModule( QualifiedName.fromString("A_Module"), """ - from project.B_Module export B_Type - type A_Type - """); + from project.B_Module export B_Type + type A_Type + """); var bMod = new SourceModule( QualifiedName.fromString("B_Module"), """ - from project.A_Module export A_Type - type B_Type - """); + from project.A_Module export A_Type + type B_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - import project.A_Module - import project.B_Module - """); + import project.A_Module + import project.B_Module + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, bMod, mainMod), projDir); expectProjectCompilationError( @@ -64,30 +64,30 @@ public void detectCycleInThreeModules() throws IOException { new SourceModule( QualifiedName.fromString("A_Module"), """ - from project.B_Module export C_Type - type A_Type - """); + from project.B_Module export C_Type + type A_Type + """); var bMod = new SourceModule( QualifiedName.fromString("B_Module"), """ - from project.C_Module export C_Type - """); + from project.C_Module export C_Type + """); var cMod = new SourceModule( QualifiedName.fromString("C_Module"), """ - from project.A_Module export A_Type - type C_Type - """); + from project.A_Module export A_Type + type C_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - import project.A_Module - import project.B_Module - import project.C_Module - """); + import project.A_Module + import project.B_Module + import project.C_Module + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, bMod, cMod, mainMod), projDir); // The reported ordering of cycle error is non-deterministic. We don't care about it. @@ -107,9 +107,9 @@ public void noCycleDetectedWhenExportingSymbolsFromItself_1() throws IOException new SourceModule( QualifiedName.fromString("Main"), """ - type Main_Type - export project.Main.Main_Type - """); + type Main_Type + export project.Main.Main_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -131,9 +131,9 @@ public void noCycleDetectedWhenExportingSymbolsFromItself_2() throws IOException new SourceModule( QualifiedName.fromString("Main"), """ - type Main_Type - from project.Main export Main_Type - """); + type Main_Type + from project.Main export Main_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportedSymbolsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportedSymbolsTest.java index 2cca38026b2a..154a2ddb8789 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportedSymbolsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ExportedSymbolsTest.java @@ -41,9 +41,11 @@ public void tearDown() throws IOException { @Test public void exportedSymbolsFromSingleModule() throws IOException { var mainSrcMod = - new SourceModule(QualifiedName.fromString("Main"), """ - type A_Type - """); + new SourceModule( + QualifiedName.fromString("Main"), + """ + type A_Type + """); ProjectUtils.createProject("Proj", Set.of(mainSrcMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -58,16 +60,18 @@ public void exportedSymbolsFromSingleModule() throws IOException { @Test public void transitivelyExportedSymbols() throws IOException { var aMod = - new SourceModule(QualifiedName.fromString("A_Module"), """ - type A_Type - """); + new SourceModule( + QualifiedName.fromString("A_Module"), + """ + type A_Type + """); var mainSrcMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.A_Module.A_Type - type B_Type - """); + export project.A_Module.A_Type + type B_Type + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainSrcMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -83,13 +87,15 @@ public void exportSymbolFromDifferentModule() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - export project.B_Module.B_Type - type A_Type - """); + export project.B_Module.B_Type + type A_Type + """); var bMod = - new SourceModule(QualifiedName.fromString("B_Module"), """ - type B_Type - """); + new SourceModule( + QualifiedName.fromString("B_Module"), + """ + type B_Type + """); ProjectUtils.createProject("Proj", Set.of(mainMod, bMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -102,15 +108,17 @@ public void exportSymbolFromDifferentModule() throws IOException { @Test public void exportRenamedSymbol() throws IOException { var aMod = - new SourceModule(QualifiedName.fromString("A_Module"), """ - type A_Type - """); + new SourceModule( + QualifiedName.fromString("A_Module"), + """ + type A_Type + """); var mainSrcMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.A_Module.A_Type as Foo - """); + export project.A_Module.A_Type as Foo + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainSrcMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -126,14 +134,14 @@ public void exportedSymbolsFromSubModule() throws IOException { new SourceModule( QualifiedName.fromString("Synthetic_Module.A_Module"), """ - type A_Module - """); + type A_Module + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - import project.Synthetic_Module - """); + import project.Synthetic_Module + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -151,15 +159,16 @@ public void exportedSymbolsFromSubModule() throws IOException { public void exportTypeFromModuleWithSameName() throws IOException { var aMod = new SourceModule( - QualifiedName.fromString("A_Module"), """ - type A_Module - """); + QualifiedName.fromString("A_Module"), + """ + type A_Module + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.A_Module.A_Module - """); + export project.A_Module.A_Module + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -177,14 +186,16 @@ public void exportTypeFromModuleWithSameName() throws IOException { public void exportModuleWithTypeWithSameName() throws IOException { var aMod = new SourceModule( - QualifiedName.fromString("A_Module"), """ - type A_Module - """); + QualifiedName.fromString("A_Module"), + """ + type A_Module + """); var mainMod = new SourceModule( - QualifiedName.fromString("Main"), """ - export project.A_Module - """); + QualifiedName.fromString("Main"), + """ + export project.A_Module + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); @@ -204,14 +215,14 @@ public void exportSyntheticModule() throws IOException { new SourceModule( QualifiedName.fromString("Synthetic_Module.A_Module"), """ - type A_Type - """); + type A_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Synthetic_Module - """); + export project.Synthetic_Module + """); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = createCtx(projDir)) { compile(ctx); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/IfThenElseTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/IfThenElseTest.java index 7a9f88ae0b53..12dbe23d6107 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/IfThenElseTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/IfThenElseTest.java @@ -23,9 +23,10 @@ public class IfThenElseTest { @Test public void simpleIfThenElse() { - var code = """ - check x = if x then "Yes" else "No" - """; + var code = + """ + check x = if x then "Yes" else "No" + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -35,9 +36,10 @@ public void simpleIfThenElse() { @Test public void simpleIfThen() { - var code = """ - check x = if x then "Yes" - """; + var code = + """ + check x = if x then "Yes" + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -47,11 +49,12 @@ public void simpleIfThen() { @Test public void variableDefinedInThen() { - var code = """ - check x = if x then - xt = x.to_text - "Good:"+xt - """; + var code = + """ + check x = if x then + xt = x.to_text + "Good:"+xt + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -63,10 +66,10 @@ public void variableDefinedInThen() { public void variableDefinedInElse() { var code = """ - check x = if x then "OKeyish:"+x.to_text else - xt = x.to_text - "Bad:"+xt - """; + check x = if x then "OKeyish:"+x.to_text else + xt = x.to_text + "Bad:"+xt + """; var check = ctxRule.getMethodFromModule(code, "check"); assertEquals("OKeyish:True", check.execute(true).asString()); @@ -78,13 +81,13 @@ public void variableUsedAfterTheBranch() { try { var code = """ - check x = - res = if x then "OKeyish:"+x.to_text else - xt = x.to_text - "Bad:"+xt + check x = + res = if x then "OKeyish:"+x.to_text else + xt = x.to_text + "Bad:"+xt - xt - """; + xt + """; var check = ctxRule.getMethodFromModule(code, "check"); fail("Expecting error, but got: " + check); @@ -99,9 +102,10 @@ public void variableUsedAfterTheBranch() { @Test public void conditionMustBeBoolean() { - var code = """ - check x = if x then "Yes" else "No" - """; + var code = + """ + check x = if x then "Yes" else "No" + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -123,13 +127,13 @@ public void conditionMustBeBoolean() { public void javaScriptBooleanIsSupported() { var code = """ - foreign js toBool txt = ''' - if (txt == "Ano") return true; - if (txt == "Ne") return false; - throw "What do you mean by: " + txt; + foreign js toBool txt = ''' + if (txt == "Ano") return true; + if (txt == "Ne") return false; + throw "What do you mean by: " + txt; - check x = if toBool x then "Yes" else "No" - """; + check x = if toBool x then "Yes" else "No" + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -142,10 +146,10 @@ public void javaScriptBooleanIsSupported() { public void truffleObjectConvertibleToBooleanIsSupported() { var code = """ - from Standard.Base import all + from Standard.Base import all - check x = if x then "Yes" else "No" - """; + check x = if x then "Yes" else "No" + """; var check = ctxRule.getMethodFromModule(code, "check"); @@ -179,18 +183,19 @@ boolean asBoolean() { public void warningsAndIfThenElse() { var code = """ - from Standard.Base import all + from Standard.Base import all - check x = if x then "Yes" else "No" - """; + check x = if x then "Yes" else "No" + """; var check = ctxRule.getMethodFromModule(code, "check"); - var warnCode = """ - from Standard.Base import all + var warnCode = + """ + from Standard.Base import all - warn w v = Warning.attach w v - """; + warn w v = Warning.attach w v + """; var warn = ctxRule.getMethodFromModule(warnCode, "warn"); var t = warn.execute("Maybe", true); @@ -207,19 +212,21 @@ public void warningsAndIfThenElse() { @Test public void warningsInThenOrElse() { - var code = """ - from Standard.Base import all + var code = + """ + from Standard.Base import all - check x y n = if x then y else n - """; + check x y n = if x then y else n + """; var check = ctxRule.getMethodFromModule(code, "check"); - var warnCode = """ - from Standard.Base import all + var warnCode = + """ + from Standard.Base import all - warn w v = Warning.attach w v - """; + warn w v = Warning.attach w v + """; var warn = ctxRule.getMethodFromModule(warnCode, "warn"); var y = warn.execute("Good", "Yes"); @@ -236,19 +243,21 @@ public void warningsInThenOrElse() { @Test public void warningsInCondAndThenOrElse() { - var code = """ - from Standard.Base import all + var code = + """ + from Standard.Base import all - check x y n = if x then y else n - """; + check x y n = if x then y else n + """; var check = ctxRule.getMethodFromModule(code, "check"); - var warnCode = """ - from Standard.Base import all + var warnCode = + """ + from Standard.Base import all - warn w v = Warning.attach w v - """; + warn w v = Warning.attach w v + """; var warn = ctxRule.getMethodFromModule(warnCode, "warn"); var y = warn.execute("Good", "Yes"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ImportsAndFQNConsistencyTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ImportsAndFQNConsistencyTest.java index f64209b1148e..2cec612d99fb 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ImportsAndFQNConsistencyTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/ImportsAndFQNConsistencyTest.java @@ -56,7 +56,8 @@ public class ImportsAndFQNConsistencyTest { @Parameters(name = "exported symbol '{0}'") public static List symbolsToTest() { var ensoCtx = ctxRule.ensoContext(); - var src = """ + var src = +""" from Standard.Base import all from Standard.Table import all main = 42 @@ -233,10 +234,8 @@ private static boolean shouldIncludeSymbolForTest( switch (binding) { case Definition.Type tp -> tp.name().name().equals(symbol); case Method.Binding methodBind -> methodBind.methodName().name().equals(symbol); - case Method.Explicit methodExplicit -> methodExplicit - .methodName() - .name() - .equals(symbol); + case Method.Explicit methodExplicit -> + methodExplicit.methodName().name().equals(symbol); default -> false; }); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypeInferenceTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypeInferenceTest.java index 90d9b4671c35..64c31ef7a277 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypeInferenceTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypeInferenceTest.java @@ -46,15 +46,15 @@ public void zeroAryCheck() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x + type My_Type + Value x - const -> My_Type = My_Type.Value 42 + const -> My_Type = My_Type.Value 42 - foo = - x = const - x - """, + foo = + x = const + x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -71,16 +71,16 @@ public void functionReturnCheck() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x + type My_Type + Value x - add x y -> My_Type = My_Type.Value (x.x+y.x) + add x y -> My_Type = My_Type.Value (x.x+y.x) - foo z = - a = My_Type.Value 42 - b = add a z - b - """, + foo z = + a = My_Type.Value 42 + b = add a z + b + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -100,20 +100,20 @@ public void argChecks() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - f1 (x1 : My_Type) = - y1 = x1 - My_Type.Value (y1.v + y1.v) + f1 (x1 : My_Type) = + y1 = x1 + My_Type.Value (y1.v + y1.v) - f2 : My_Type -> My_Type - f2 x2 = - y2 = x2 - My_Type.Value (y2.v + y2.v) + f2 : My_Type -> My_Type + f2 x2 = + y2 = x2 + My_Type.Value (y2.v + y2.v) - f3 (x3 : My_Type) -> My_Type = My_Type.Value (x3.v + x3.v) - """, + f3 (x3 : My_Type) -> My_Type = My_Type.Value (x3.v + x3.v) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -141,13 +141,13 @@ public void ascribedExpressions() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x + type My_Type + Value x - f x = - y = (x : My_Type) - My_Type.Value (y.x + y.x) - """, + f x = + y = (x : My_Type) + My_Type.Value (y.x + y.x) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -166,15 +166,15 @@ public void advancedAscribedExpressions() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x - type Other_Type - Value y - f z = - y1 = (z : My_Type | Other_Type) - y2 = (z : My_Type & Other_Type) - My_Type.Value (y1.x + y2.x) - """, + type My_Type + Value x + type Other_Type + Value y + f z = + y1 = (z : My_Type | Other_Type) + y2 = (z : My_Type & Other_Type) + My_Type.Value (y1.x + y2.x) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -209,15 +209,15 @@ public void ascribedFunctionType() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x - type Other_Type - Value y - f z w = - f1 = (z : My_Type -> Other_Type) - f2 = (w : My_Type -> My_Type -> Other_Type) - f2 (f1 (My_Type.Value 42)) - """, + type My_Type + Value x + type Other_Type + Value y + f z w = + f1 = (z : My_Type -> Other_Type) + f2 = (w : My_Type -> My_Type -> Other_Type) + f2 (f1 (My_Type.Value 42)) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -245,13 +245,13 @@ public void literals() throws Exception { Source.newBuilder( "enso", """ - f = - x = 42 - y = "foo" - z = 1.5 - w = [1, 2, 3] - x.to_text + y + z.to_text + w.to_text - """, + f = + x = 42 + y = "foo" + z = 1.5 + w = [1, 2, 3] + x.to_text + y + z.to_text + w.to_text + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -272,14 +272,14 @@ public void bindingsFlow() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - foo x = - y = (x : My_Type) - z = y - w = z - w - """, + type My_Type + Value v + foo x = + y = (x : My_Type) + z = y + w = z + w + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -299,13 +299,13 @@ public void checkedArgumentTypes() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - foo (x1 : My_Type) x2 = - y1 = x1 - y2 = x2 - [y1, y2] - """, + type My_Type + Value v + foo (x1 : My_Type) x2 = + y1 = x1 + y2 = x2 + [y1, y2] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -329,15 +329,15 @@ public void innerFunctionType() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - foo = - f (x : My_Type) (y : My_Type) -> My_Type = My_Type.Value x.v+y.v - - f1 = f - y = f (My_Type.Value 1) (My_Type.Value 2) - [y, f1] - """, + type My_Type + Value v + foo = + f (x : My_Type) (y : My_Type) -> My_Type = My_Type.Value x.v+y.v + + f1 = f + y = f (My_Type.Value 1) (My_Type.Value 2) + [y, f1] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -359,13 +359,13 @@ public void zeroArgConstructor() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Singleton - foo = - # x = zeroArgConstructor.My_Type - x = My_Type.Singleton - x - """, + type My_Type + Singleton + foo = + # x = zeroArgConstructor.My_Type + x = My_Type.Singleton + x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -384,12 +384,12 @@ public void multiArgConstructor() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x y z - foo = - x = My_Type.Value 1 2 3 - x - """, + type My_Type + Value x y z + foo = + x = My_Type.Value 1 2 3 + x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -408,12 +408,12 @@ public void nonexistentConstructor() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x y z - foo = - x = My_Type.Non_Existent 1 - x - """, + type My_Type + Value x y z + foo = + x = My_Type.Non_Existent 1 + x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -438,19 +438,19 @@ public void constructorWithDefaults() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value x y=100 z=200 - All_Defaults a=1000 b=2000 - foo = - x1 = My_Type.Value 1 2 3 - x2 = My_Type.Value 1 2 - x3 = My_Type.Value 1 - x4 = My_Type.Value - x5 = My_Type.Value 1 ... - x6 = My_Type.All_Defaults - x7 = My_Type.All_Defaults ... - [x1, x2, x3, x4, x5, x6, x7] - """, + type My_Type + Value x y=100 z=200 + All_Defaults a=1000 b=2000 + foo = + x1 = My_Type.Value 1 2 3 + x2 = My_Type.Value 1 2 + x3 = My_Type.Value 1 + x4 = My_Type.Value + x5 = My_Type.Value 1 ... + x6 = My_Type.All_Defaults + x7 = My_Type.All_Defaults ... + [x1, x2, x3, x4, x5, x6, x7] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -493,10 +493,10 @@ public void commonIfThenElse() throws Exception { Source.newBuilder( "enso", """ - f x = - y = if x == 10 then 1 else 2 - y - """, + f x = + y = if x == 10 then 1 else 2 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -513,15 +513,15 @@ public void commonCase() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - f x = - y = case x of - 1 -> My_Type.Value 1 - 2 -> My_Type.Value 20 - _ -> My_Type.Value 300 - y - """, + type My_Type + Value v + f x = + y = case x of + 1 -> My_Type.Value 1 + 2 -> My_Type.Value 20 + _ -> My_Type.Value 300 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -539,14 +539,14 @@ public void inferBoundsFromCaseAlias() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - f x = - y = case x of - i : My_Type -> i - _ -> My_Type.Value 0 - y - """, + type My_Type + Value v + f x = + y = case x of + i : My_Type -> i + _ -> My_Type.Value 0 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -570,14 +570,14 @@ public void inferEqualityBoundsFromCase() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - f x = - y = case x of - _ : My_Type -> x - _ -> My_Type.Value 42 - y - """, + type My_Type + Value v + f x = + y = case x of + _ : My_Type -> x + _ -> My_Type.Value 42 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -596,12 +596,12 @@ public void inferEqualityBoundsFromCaseLiteral() throws Exception { Source.newBuilder( "enso", """ - f x = - y = case x of - 1 -> x - "foo" -> x - y - """, + f x = + y = case x of + 1 -> x + "foo" -> x + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -621,16 +621,16 @@ public void inferEqualityBoundsFromCaseEdgeCase() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - f x = - y = case x of - _ : Other_Type -> My_Type.Value 42 - _ : My_Type -> x - y - """, + type My_Type + Value v + type Other_Type + Value o + f x = + y = case x of + _ : Other_Type -> My_Type.Value 42 + _ : My_Type -> x + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -648,16 +648,16 @@ public void sumTypeFromCase() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - f x = - y = case x of - 1 -> My_Type.Value 42 - 2 -> Other_Type.Value 23 - y - """, + type My_Type + Value v + type Other_Type + Value o + f x = + y = case x of + 1 -> My_Type.Value 42 + 2 -> Other_Type.Value 23 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -675,10 +675,10 @@ public void sumTypeFromIf() throws Exception { Source.newBuilder( "enso", """ - f x = - y = if x == 1 then "foo" else 42 - y - """, + f x = + y = if x == 1 then "foo" else 42 + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -696,10 +696,10 @@ public void sumTypeFromIfWithoutElse() throws Exception { Source.newBuilder( "enso", """ - f x = - y = if x == 1 then "foo" - y - """, + f x = + y = if x == 1 then "foo" + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -716,21 +716,21 @@ public void typeInferenceWorksInsideMemberMethods() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - - static_method (x : My_Type) = - y = x - z = My_Type.Value 23 - w = 42 - [y, z, w] - - member_method self (x : My_Type) = - y = x - z = My_Type.Value 23 - w = 42 - [y, z, w] - """, + type My_Type + Value v + + static_method (x : My_Type) = + y = x + z = My_Type.Value 23 + w = 42 + [y, z, w] + + member_method self (x : My_Type) = + y = x + z = My_Type.Value 23 + w = 42 + [y, z, w] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -759,13 +759,13 @@ public void typeInferenceOfSelf() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - member_method self = - y = self - y - """, + member_method self = + y = self + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -783,13 +783,13 @@ public void notInvokable() throws Exception { Source.newBuilder( "enso", """ - type My_Type - foo unknown = - x1 = 0 1 - x2 = "a" 2 - x3 = unknown 3 - [x1, x2, x3] - """, + type My_Type + foo unknown = + x1 = 0 1 + x2 = "a" 2 + x3 = unknown 3 + [x1, x2, x3] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -825,16 +825,16 @@ public void noErrorInParametricTypeSignatures() throws Exception { Source.newBuilder( "enso", """ - type My_Type a - Value v - type Other_Type - Value (v : My_Type Other_Type) + type My_Type a + Value v + type Other_Type + Value (v : My_Type Other_Type) - foo1 : My_Type Other_Type -> My_Type Other_Type - foo1 v = v + foo1 : My_Type Other_Type -> My_Type Other_Type + foo1 v = v - foo2 (v : My_Type Other_Type) -> My_Type Other_Type = v - """, + foo2 (v : My_Type Other_Type) -> My_Type Other_Type = v + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -850,20 +850,20 @@ public void noTypeErrorIfConversionExists() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 - - function_taking_other o:Other_Type = - o.o - - foo = - x = My_Type.Value 12 - y = function_taking_other x - y - """, + type My_Type + Value v + type Other_Type + Value o + Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 + + function_taking_other o:Other_Type = + o.o + + foo = + x = My_Type.Value 12 + y = function_taking_other x + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -885,12 +885,12 @@ public void noTypeErrorIfConversionExistsInTypeScope() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 - """, + type My_Type + Value v + type Other_Type + Value o + Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 + """, uriA.getAuthority()) .uri(uriA) .buildLiteral(); @@ -901,16 +901,16 @@ public void noTypeErrorIfConversionExistsInTypeScope() throws Exception { Source.newBuilder( "enso", """ - from local.Project1.typeDef import My_Type, Other_Type + from local.Project1.typeDef import My_Type, Other_Type - function_taking_other o:Other_Type = - o.o + function_taking_other o:Other_Type = + o.o - foo = - x = My_Type.Value 12 - y = function_taking_other x - y - """, + foo = + x = My_Type.Value 12 + y = function_taking_other x + y + """, uriB.getAuthority()) .uri(uriB) .buildLiteral(); @@ -932,11 +932,11 @@ public void noTypeErrorIfConversionIsImported() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - """, + type My_Type + Value v + type Other_Type + Value o + """, uriA.getAuthority()) .uri(uriA) .buildLiteral(); @@ -947,9 +947,9 @@ public void noTypeErrorIfConversionIsImported() throws Exception { Source.newBuilder( "enso", """ - from local.Project1.typeDef import My_Type, Other_Type - Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 - """, + from local.Project1.typeDef import My_Type, Other_Type + Other_Type.from (that : My_Type) = Other_Type.Value that.v+1000 + """, uriB.getAuthority()) .uri(uriB) .buildLiteral(); @@ -960,16 +960,16 @@ public void noTypeErrorIfConversionIsImported() throws Exception { Source.newBuilder( "enso", """ - from local.Project1.typeDef import My_Type, Other_Type + from local.Project1.typeDef import My_Type, Other_Type - function_taking_other o:Other_Type = - o.o + function_taking_other o:Other_Type = + o.o - foo = - x = My_Type.Value 12 - y = function_taking_other x - y - """, + foo = + x = My_Type.Value 12 + y = function_taking_other x + y + """, uriC.getAuthority()) .uri(uriC) .buildLiteral(); @@ -985,17 +985,17 @@ public void noTypeErrorIfConversionIsImported() throws Exception { Source.newBuilder( "enso", """ - from local.Project1.typeDef import My_Type, Other_Type - from local.Project1.conversionDef import all + from local.Project1.typeDef import My_Type, Other_Type + from local.Project1.conversionDef import all - function_taking_other o:Other_Type = - o.o + function_taking_other o:Other_Type = + o.o - foo = - x = My_Type.Value 12 - y = function_taking_other x - y - """, + foo = + x = My_Type.Value 12 + y = function_taking_other x + y + """, uriD.getAuthority()) .uri(uriD) .buildLiteral(); @@ -1015,22 +1015,22 @@ public void typeErrorFunctionToObject() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - - foo = - f x = x - takes_my_type (m : My_Type) = m - y1 = takes_my_type f - g (x : My_Type) -> My_Type = x - y2 = takes_my_type g - - takes_function (f : Any -> Any) = f - y3 = takes_function (My_Type.Value 123) - y4 = takes_function My_Type.Value - y5 = takes_function f - [y1, y2, y3, y4, y5] - """, + type My_Type + Value v + + foo = + f x = x + takes_my_type (m : My_Type) = m + y1 = takes_my_type f + g (x : My_Type) -> My_Type = x + y2 = takes_my_type g + + takes_function (f : Any -> Any) = f + y3 = takes_function (My_Type.Value 123) + y4 = takes_function My_Type.Value + y5 = takes_function f + [y1, y2, y3, y4, y5] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1062,16 +1062,16 @@ public void typeErrorInLocalCall() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - type Other_Type - Value o - foo = - bar (x : Other_Type) = x - y = My_Type.Value 10 - z = bar y - z - """, + type My_Type + Value v + type Other_Type + Value o + foo = + bar (x : Other_Type) = x + y = My_Type.Value 10 + z = bar y + z + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1083,8 +1083,9 @@ public void typeErrorInLocalCall() throws Exception { var arg = switch (z.expression()) { case Application.Prefix app -> app.arguments().head(); - default -> throw new AssertionError( - "Expected " + z.showCode() + " to be an application expression."); + default -> + throw new AssertionError( + "Expected " + z.showCode() + " to be an application expression."); }; var typeError = new Warning.TypeMismatch(arg.identifiedLocation(), "Other_Type", "My_Type"); assertEquals(List.of(typeError), ModuleUtils.getImmediateDiagnostics(arg)); @@ -1098,12 +1099,12 @@ public void typeErrorInReturn() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - foo = - x -> My_Type = 10 - x - """, + type My_Type + Value v + foo = + x -> My_Type = 10 + x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1122,15 +1123,15 @@ public void noTypeErrorIfUnsure() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - foo unknown = - bar (x : My_Type) = x - baz -> My_Type = unknown - y = bar unknown - z = (unknown : My_Type) - [y, z] - """, + type My_Type + Value v + foo unknown = + bar (x : My_Type) = x + baz -> My_Type = unknown + y = bar unknown + z = (unknown : My_Type) + [y, z] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1164,18 +1165,18 @@ public void globalMethodTypes() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - - const -> My_Type = My_Type.Value 23 - check (x : My_Type) -> My_Type = x - - foo = - x1 = const - x2 = check - x3 = check const - [x1, x2, x3] - """, + type My_Type + Value v + + const -> My_Type = My_Type.Value 23 + check (x : My_Type) -> My_Type = x + + foo = + x1 = const + x2 = check + x3 = check const + [x1, x2, x3] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1198,33 +1199,33 @@ public void memberMethodCalls() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - zero_arg self -> My_Type = My_Type.Value [self.v] - one_arg self (x : My_Type) -> My_Type = My_Type.Value [self.v, x.v] + zero_arg self -> My_Type = My_Type.Value [self.v] + one_arg self (x : My_Type) -> My_Type = My_Type.Value [self.v, x.v] - static_zero -> My_Type = My_Type.Value 42 - static_one (x : My_Type) -> My_Type = My_Type.Value [x.v, 1] + static_zero -> My_Type = My_Type.Value 42 + static_one (x : My_Type) -> My_Type = My_Type.Value [x.v, 1] - My_Type.extension_method self -> My_Type = My_Type.Value [self.v, 2] + My_Type.extension_method self -> My_Type = My_Type.Value [self.v, 2] - foo = - inst = My_Type.Value 23 - x1 = inst.zero_arg - x2 = inst.one_arg inst - x3 = My_Type.static_zero - x4 = My_Type.static_one inst + foo = + inst = My_Type.Value 23 + x1 = inst.zero_arg + x2 = inst.one_arg inst + x3 = My_Type.static_zero + x4 = My_Type.static_one inst - # And calling member methods through static syntax: - x5 = My_Type.zero_arg inst - x6 = My_Type.one_arg inst + # And calling member methods through static syntax: + x5 = My_Type.zero_arg inst + x6 = My_Type.one_arg inst - # And extension methods - x7 = inst.extension_method - x8 = My_Type.extension_method inst - [x1, x2, x3, x4, x5, x6, x7, x8] - """, + # And extension methods + x7 = inst.extension_method + x8 = My_Type.extension_method inst + [x1, x2, x3, x4, x5, x6, x7, x8] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1256,21 +1257,21 @@ public void staticCallWithWrongType() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - member_method self = [self.v] + member_method self = [self.v] - type Other_Type - Constructor v + type Other_Type + Constructor v - member_method = [self.v, self.v] + member_method = [self.v, self.v] - foo = - other = Other_Type.Constructor 44 - x1 = My_Type.member_method other - x1 - """, + foo = + other = Other_Type.Constructor 44 + x1 = My_Type.member_method other + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1289,14 +1290,14 @@ public void defaultArgumentWithWrongType() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - type Other_Type - Constructor v + type Other_Type + Constructor v - foo (arg : My_Type = Other_Type.Constructor 1) = arg - """, + foo (arg : My_Type = Other_Type.Constructor 1) = arg + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1320,14 +1321,14 @@ public void returnWrongType() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - type Other_Type - Constructor v + type Other_Type + Constructor v - foo -> My_Type = Other_Type.Constructor 1 - """, + foo -> My_Type = Other_Type.Constructor 1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1344,24 +1345,24 @@ public void callingFieldGetters() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Constructor_1 (field_a : Typ_X) (field_b : Typ_Y) - Constructor_2 (field_b : Typ_Z) - Constructor_3 (field_c : Typ_Z) - Constructor_4 (field_c : Typ_Z) - Constructor_5 field_d - - type Typ_X - type Typ_Y - type Typ_Z - - foo (instance : My_Type) = - x_a = instance.field_a - x_b = instance.field_b - x_c = instance.field_c - x_d = instance.field_d - [x_a, x_b, x_c, x_d] - """, + type My_Type + Constructor_1 (field_a : Typ_X) (field_b : Typ_Y) + Constructor_2 (field_b : Typ_Z) + Constructor_3 (field_c : Typ_Z) + Constructor_4 (field_c : Typ_Z) + Constructor_5 field_d + + type Typ_X + type Typ_Y + type Typ_Z + + foo (instance : My_Type) = + x_a = instance.field_a + x_b = instance.field_b + x_c = instance.field_c + x_d = instance.field_d + [x_a, x_b, x_c, x_d] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1393,23 +1394,23 @@ public void noSuchMethodStaticCheck() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Any.Any - - type My_Type - Value v - - method_one self = 42 - static_method = 44 - - foo = - inst = My_Type.Value 23 - x1 = inst.method_one - x2 = inst.method_two - x3 = inst.to_text - x4 = inst.is_error - x5 = inst.static_method - [x1, x2, x3, x4, x5] - """, + import Standard.Base.Any.Any + + type My_Type + Value v + + method_one self = 42 + static_method = 44 + + foo = + inst = My_Type.Value 23 + x1 = inst.method_one + x2 = inst.method_two + x3 = inst.to_text + x4 = inst.is_error + x5 = inst.static_method + [x1, x2, x3, x4, x5] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1454,18 +1455,18 @@ public void noSuchMethodInsideMethodWithDefaultArgs() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Any.Any - - type My_Type - Value v - method_one self = 42 - - foo arg1 arg2="default" = - inst = My_Type.Value 23 - x1 = inst.method_one - x2 = inst.nonexistent - [x1, x2] - """, + import Standard.Base.Any.Any + + type My_Type + Value v + method_one self = 42 + + foo arg1 arg2="default" = + inst = My_Type.Value 23 + x1 = inst.method_one + x2 = inst.nonexistent + [x1, x2] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1494,17 +1495,17 @@ public void alwaysKnowsMethodsOfAny() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v + type My_Type + Value v - foo x = - txt1 = x.to_text - txt2 = 42.to_text - txt3 = (My_Type.Value 1).to_text + foo x = + txt1 = x.to_text + txt2 = 42.to_text + txt3 = (My_Type.Value 1).to_text - bool = (x == x) - [txt1, txt2, txt3, bool] - """, + bool = (x == x) + [txt1, txt2, txt3, bool] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1527,15 +1528,15 @@ public void noSuchMethodOnSelf() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - - method_one self = 42 - method_two self = - x1 = self.method_one - x2 = self.non_existent_method - [x1, x2] - """, + type My_Type + Value v + + method_one self = 42 + method_two self = + x1 = self.method_one + x2 = self.non_existent_method + [x1, x2] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1564,9 +1565,9 @@ public void callingExtensionMethodDefinedElsewhere() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - """, + type My_Type + Value v + """, uriA.getAuthority()) .uri(uriA) .buildLiteral(); @@ -1577,16 +1578,16 @@ public void callingExtensionMethodDefinedElsewhere() throws Exception { Source.newBuilder( "enso", """ - import local.Project1.modA.My_Type + import local.Project1.modA.My_Type - type Typ_X - Value a - type Typ_Y - Value a + type Typ_X + Value a + type Typ_Y + Value a - My_Type.member self -> Typ_X = Typ_X.Value self - My_Type.static -> Typ_Y = Typ_Y.Value 32 - """, + My_Type.member self -> Typ_X = Typ_X.Value self + My_Type.static -> Typ_Y = Typ_Y.Value 32 + """, uriB.getAuthority()) .uri(uriB) .buildLiteral(); @@ -1597,15 +1598,15 @@ public void callingExtensionMethodDefinedElsewhere() throws Exception { Source.newBuilder( "enso", """ - import local.Project1.modA.My_Type - from local.Project1.modB import all - - foo = - inst = My_Type.Value 23 - x1 = inst.member - x2 = My_Type.static - [x1, x2] - """, + import local.Project1.modA.My_Type + from local.Project1.modB import all + + foo = + inst = My_Type.Value 23 + x1 = inst.member + x2 = My_Type.static + [x1, x2] + """, uriC.getAuthority()) .uri(uriC) .buildLiteral(); @@ -1624,9 +1625,9 @@ public void callingReexportedExtensionMethods() throws Exception { Source.newBuilder( "enso", """ - type My_Type - Value v - """, + type My_Type + Value v + """, uriA.getAuthority()) .uri(uriA) .buildLiteral(); @@ -1638,16 +1639,16 @@ public void callingReexportedExtensionMethods() throws Exception { Source.newBuilder( "enso", """ - import local.Project1.modA.My_Type + import local.Project1.modA.My_Type - type Typ_X - Value a - type Typ_Y - Value a + type Typ_X + Value a + type Typ_Y + Value a - My_Type.member self -> Typ_X = Typ_X.Value self - My_Type.static -> Typ_Y = Typ_Y.Value 32 - """, + My_Type.member self -> Typ_X = Typ_X.Value self + My_Type.static -> Typ_Y = Typ_Y.Value 32 + """, uriB.getAuthority()) .uri(uriB) .buildLiteral(); @@ -1659,9 +1660,9 @@ public void callingReexportedExtensionMethods() throws Exception { Source.newBuilder( "enso", """ - export local.Project1.modA.My_Type - export local.Project1.modB.member - """, + export local.Project1.modA.My_Type + export local.Project1.modB.member + """, uriC.getAuthority()) .uri(uriC) .buildLiteral(); @@ -1672,14 +1673,14 @@ public void callingReexportedExtensionMethods() throws Exception { Source.newBuilder( "enso", """ - from local.Project1.modC import all - - foo = - inst = My_Type.Value 23 - x1 = inst.member - x2 = My_Type.static - [x1, x2] - """, + from local.Project1.modC import all + + foo = + inst = My_Type.Value 23 + x1 = inst.member + x2 = My_Type.static + [x1, x2] + """, uriD.getAuthority()) .uri(uriD) .buildLiteral(); @@ -1697,15 +1698,15 @@ public void resolveImportedConstructor() throws Exception { Source.newBuilder( "enso", """ - from project.modA.My_Type import My_Constructor + from project.modA.My_Type import My_Constructor - type My_Type - My_Constructor v + type My_Type + My_Constructor v - foo = - x1 = My_Constructor 1 - x1 - """, + foo = + x1 = My_Constructor 1 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1724,13 +1725,13 @@ public void resolveFQNConstructor() throws Exception { Source.newBuilder( "enso", """ - type My_Type - My_Constructor v + type My_Type + My_Constructor v - foo = - x1 = local.Project1.modA.My_Type.My_Constructor 1 - x1 - """, + foo = + x1 = local.Project1.modA.My_Type.My_Constructor 1 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1747,43 +1748,43 @@ public static Source anyPrecedenceTestSource() throws URISyntaxException { Source.newBuilder( "enso", """ - import Standard.Base.Any.Any - - type A - A_Value - type B - B_Value - type C - C_Value - type D - D_Value - type E - E_Value - - Any.method self -> A = A.A_Value - Any.static_method -> D = D.D_Value - - type My_Type - Value - - method self -> B = B.B_Value - static_method -> E = E.E_Value - - type Other_Type - Value - - method -> C = C.C_Value - - foo = - x1 = Other_Type.Value.method - x2 = My_Type.Value.method - x3 = method - x4 = My_Type.method - x5 = Any.method My_Type.Value - x6 = Any.static_method - x7 = My_Type.static_method - [x1, x2, x3, x4, x5, x6, x7] - """, + import Standard.Base.Any.Any + + type A + A_Value + type B + B_Value + type C + C_Value + type D + D_Value + type E + E_Value + + Any.method self -> A = A.A_Value + Any.static_method -> D = D.D_Value + + type My_Type + Value + + method self -> B = B.B_Value + static_method -> E = E.E_Value + + type Other_Type + Value + + method -> C = C.C_Value + + foo = + x1 = Other_Type.Value.method + x2 = My_Type.Value.method + x3 = method + x4 = My_Type.method + x5 = Any.method My_Type.Value + x6 = Any.static_method + x7 = My_Type.static_method + [x1, x2, x3, x4, x5, x6, x7] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1798,15 +1799,15 @@ public void overrideMethodOnNumberThroughAny() throws URISyntaxException { Source.newBuilder( "enso", """ - type A - A_Value + type A + A_Value - Any.method self -> A = A.A_Value + Any.method self -> A = A.A_Value - foo = - x1 = 42.method - x1 - """, + foo = + x1 = 42.method + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1858,12 +1859,12 @@ public void missingFunctionArgumentWarning() throws Exception { Source.newBuilder( "enso", """ - my_function a b c = [a, b, c] - foo = - # This call has no effect as the result is discarded but no function was called either. - my_function 1 - 0 - """, + my_function a b c = [a, b, c] + foo = + # This call has no effect as the result is discarded but no function was called either. + my_function 1 + 0 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypesFromSignaturesTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypesFromSignaturesTest.java index 790cdd253776..b6d15d77ec69 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypesFromSignaturesTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/TypesFromSignaturesTest.java @@ -25,13 +25,13 @@ public void simpleCheck() throws Exception { Source.newBuilder( "enso", """ - type A - type B - type C - Value v + type A + type B + type C + Value v - f (x : A) (y : B) -> C = C.Value [x, y] - """, + f (x : A) (y : B) -> C = C.Value [x, y] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -48,21 +48,21 @@ public void variousExpressions() throws Exception { Source.newBuilder( "enso", """ - type A - Value - + self other = other - type B - - f1 (_ : A) -> B = 1 - f2 (x : A) -> B = x + 10 - f3 (x : A) -> B = [x] - f4 (x : A) -> B = f1 x - f5 (x : A) -> B = x - f6 (x : A) -> B = - y = x - z = y - z - """, + type A + Value + + self other = other + type B + + f1 (_ : A) -> B = 1 + f2 (x : A) -> B = x + 10 + f3 (x : A) -> B = [x] + f4 (x : A) -> B = f1 x + f5 (x : A) -> B = x + f6 (x : A) -> B = + y = x + z = y + z + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -83,18 +83,18 @@ public void justArity() throws Exception { Source.newBuilder( "enso", """ - type A - type B - type C - Value v + type A + type B + type C + Value v - f0 = 0 + f0 = 0 - f4 x y z w = [x, y, z, w] + f4 x y z w = [x, y, z, w] - f2 : A -> B -> C - f2 x y = [x, y] - """, + f2 : A -> B -> C + f2 x y = [x, y] + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -126,11 +126,11 @@ public void memberMethods() throws URISyntaxException { Source.newBuilder( "enso", """ - type A - static_method (x : A) -> A = x - member_method self (x : A) -> A = x - standalone_method (x : A) -> A = x - """, + type A + static_method (x : A) -> A = x + member_method self (x : A) -> A = x + standalone_method (x : A) -> A = x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -150,11 +150,11 @@ public void extensionMethods() throws URISyntaxException { Source.newBuilder( "enso", """ - type A + type A - A.extension_static_method (x : A) -> A = x - A.extension_member_method self (x : A) -> A = x - """, + A.extension_static_method (x : A) -> A = x + A.extension_member_method self (x : A) -> A = x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/WarningsAsErrorsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/WarningsAsErrorsTest.java index 44805cfb28eb..de086d19ef4d 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/WarningsAsErrorsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/WarningsAsErrorsTest.java @@ -21,20 +21,24 @@ public class WarningsAsErrorsTest { @Test public void warningCausesCompilerFailure() { try { - var module = ctxRule.eval("enso", """ - foo = - unused = 1 - 2 - """); + var module = + ctxRule.eval( + "enso", + """ + foo = + unused = 1 + 2 + """); fail("Expecting an error but got: " + module); } catch (PolyglotException ex) { assertTrue("Syntax error", ex.isSyntaxError()); assertTrue("Guest exception", ex.isGuestException()); assertEquals( """ - Unnamed:2:5: warning: Unused variable unused. - 2 | unused = 1 - | ^~~~~~""", + Unnamed:2:5: warning: Unused variable unused. + 2 | unused = 1 + | ^~~~~~\ + """, ex.getMessage()); } } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/passes/resolve/NameResolutionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/passes/resolve/NameResolutionTest.java index b2873c48941d..fcd72cb2688f 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/passes/resolve/NameResolutionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/compiler/test/passes/resolve/NameResolutionTest.java @@ -51,18 +51,21 @@ public final class NameResolutionTest { @Test public void libraryNameIsResolved_InExpressionBlock() throws IOException { - var myMod = srcModule("My_Module", """ - type My_Type - """); + var myMod = + srcModule( + "My_Module", + """ + type My_Type + """); var mainMod = srcModule( "Main", """ - import project.My_Module.My_Type + import project.My_Module.My_Type - main = - local.Proj.My_Module.My_Type - """); + main = + local.Proj.My_Module.My_Type + """); withProject( "Proj", Set.of(myMod, mainMod), @@ -89,18 +92,21 @@ public void libraryNameIsResolved_InExpressionBlock() throws IOException { @Test public void importedNameIsResolved_AsType() throws Exception { - var myMod = srcModule("My_Module", """ - type My_Type - """); + var myMod = + srcModule( + "My_Module", + """ + type My_Type + """); var mainMod = srcModule( "Main", """ - import project.My_Module.My_Type + import project.My_Module.My_Type - main = - My_Type - """); + main = + My_Type + """); withProject( "Proj", Set.of(myMod, mainMod), @@ -127,19 +133,22 @@ public void importedNameIsResolved_AsType() throws Exception { */ @Test public void nameIsResolved_InAscribedType() throws Exception { - var myMod = srcModule("My_Module", """ - type My_Type - Cons - """); + var myMod = + srcModule( + "My_Module", + """ + type My_Type + Cons + """); var mainMod = srcModule( "Main", """ - import project.My_Module.My_Type + import project.My_Module.My_Type - foo : local.Proj.My_Module.My_Type - foo = My_Type.Cons - """); + foo : local.Proj.My_Module.My_Type + foo = My_Type.Cons + """); withProject( "Proj", Set.of(myMod, mainMod), @@ -172,19 +181,19 @@ public void nameIsResolved_InInlineAscription() throws Exception { srcModule( "My_Module", """ - type My_Type - Cons - method self = 42 - """); + type My_Type + Cons + method self = 42 + """); var mainMod = srcModule( "Main", """ - import project.My_Module.My_Type + import project.My_Module.My_Type - foo (obj : local.Proj.My_Module.My_Type) = - obj.method - """); + foo (obj : local.Proj.My_Module.My_Type) = + obj.method + """); withProject( "Proj", Set.of(myMod, mainMod), @@ -225,17 +234,18 @@ public void nameIsResolved_InInlineAscription_TwoProjects() throws Exception { method self = 42 """), srcModule( - "Main", """ + "Main", + """ export project.My_Module.My_Type """)), libDir); ProjectUtils.createProject( "Proj", """ - from local.Lib import all + from local.Lib import all - foo (obj : local.Lib.My_Module.My_Type) = obj.method - """, + foo (obj : local.Lib.My_Module.My_Type) = obj.method + """, projDir); try (var ctx = createCtx(projDir)) { compileAllModules(ctx); @@ -268,7 +278,9 @@ public void nameIsResolved_InExpression_TwoProjects_TypeInSubmodule() throws Exc ProjectUtils.createProject( "Lib", Set.of( - srcModule("Data.Numbers", """ + srcModule( + "Data.Numbers", + """ type Integer """), srcModule( @@ -280,11 +292,11 @@ public void nameIsResolved_InExpression_TwoProjects_TypeInSubmodule() throws Exc ProjectUtils.createProject( "Proj", """ - from local.Lib import all + from local.Lib import all - main = - local.Lib.Data.Numbers.Integer - """, + main = + local.Lib.Data.Numbers.Integer + """, projDir); try (var ctx = createCtx(projDir)) { compileAllModules(ctx); @@ -315,7 +327,9 @@ public void nameIsResolved_InInlineAscription_TwoProjects_TypeInSubmodule() thro ProjectUtils.createProject( "Lib", Set.of( - srcModule("Data.Numbers", """ + srcModule( + "Data.Numbers", + """ type Integer """), srcModule( @@ -327,10 +341,10 @@ public void nameIsResolved_InInlineAscription_TwoProjects_TypeInSubmodule() thro ProjectUtils.createProject( "Proj", """ - from local.Lib import all + from local.Lib import all - foo (obj : local.Lib.Data.Numbers.Integer) = obj - """, + foo (obj : local.Lib.Data.Numbers.Integer) = obj + """, projDir); try (var ctx = createCtx(projDir)) { compileAllModules(ctx); @@ -362,21 +376,24 @@ public void nameIsResolved_InInlineAscription_TwoProjects_TypeInSubmodule() thro */ @Test public void libNameIsResolved_InCaseBranch() throws Exception { - var myMod = srcModule("My_Module", """ - type My_Type - """); + var myMod = + srcModule( + "My_Module", + """ + type My_Type + """); var mainMod = srcModule( "Main", """ - import project.My_Module.My_Type + import project.My_Module.My_Type - main = - x = 42 - case x of - _ : local.Proj.My_Module.My_Type -> 21 # Case.Branch - _ -> 22 - """); + main = + x = 42 + case x of + _ : local.Proj.My_Module.My_Type -> 21 # Case.Branch + _ -> 22 + """); withProject( "Proj", Set.of(myMod, mainMod), @@ -418,11 +435,14 @@ public void libNameIsResolved_FromDifferentProject() throws IOException { ProjectUtils.createProject( "Lib", Set.of( - srcModule("My_Module", """ + srcModule( + "My_Module", + """ type My_Type """), srcModule( - "Main", """ + "Main", + """ export project.My_Module.My_Type """)), libDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/HelloWorldCacheTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/HelloWorldCacheTest.java index 5c40840ae919..b3e4c0725db5 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/HelloWorldCacheTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/HelloWorldCacheTest.java @@ -84,9 +84,9 @@ public void runningAfterPrivateCheckWasDisabled_ShouldFail() throws Exception { new SourceModule( QualifiedName.fromString("Priv_Mod"), """ - private - priv_func x = x - """), + private + priv_func x = x + """), new SourceModule(QualifiedName.fromString("Main"), "# Intentionally empty")), libDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/IRCacheLocationTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/IRCacheLocationTest.java index 39fa78c7a6fb..d0f0e6add6a3 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/IRCacheLocationTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/IRCacheLocationTest.java @@ -31,10 +31,12 @@ public static void skipOnWindows() { public void noGlobalCacheOption_IsRespected() throws IOException { var projDir = tmpDir.newFolder(); ProjectUtils.createProject( - "Proj", """ + "Proj", + """ main = 42 - """, projDir.toPath()); + """, + projDir.toPath()); var mainSrcPath = projDir.toPath().resolve("src").resolve("Main.enso"); try (var ctx = @@ -63,10 +65,12 @@ public void noGlobalCacheOption_IsRespected() throws IOException { public void irCacheIsCreatedAlsoForDependencies() throws IOException { var libDir = tmpDir.newFolder("Lib"); ProjectUtils.createProject( - "Lib", """ + "Lib", + """ lib_method = 42 - """, libDir.toPath()); + """, + libDir.toPath()); var projDir = tmpDir.newFolder("Proj"); ProjectUtils.createProject( diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/ModuleCacheTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/ModuleCacheTest.java index 587468ffb524..b962636ac539 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/ModuleCacheTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/caches/ModuleCacheTest.java @@ -30,11 +30,13 @@ public void testCompareList() throws Exception { var v = ctxRule - .eval("enso", """ - import Standard.Base.Data.List + .eval( + "enso", + """ + import Standard.Base.Data.List - empty = List.List.Nil - """) + empty = List.List.Nil + """) .invokeMember(MethodNames.Module.EVAL_EXPRESSION, "empty"); assertEquals("List", v.getMetaObject().getMetaSimpleName()); @@ -58,9 +60,13 @@ public void testCompareWithWarning() throws Exception { var ensoCtx = ctxRule.ensoContext(); var name = "TestWarning"; var code = - Source.newBuilder("enso", """ - empty x = 42 - """, "TestWarning.enso").build(); + Source.newBuilder( + "enso", + """ + empty x = 42 + """, + "TestWarning.enso") + .build(); var v = ctxRule.eval(code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "empty").execute(-1); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/ProgramRootNodeTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/ProgramRootNodeTest.java index 0cd340cec96d..1bbabc0e6598 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/ProgramRootNodeTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/ProgramRootNodeTest.java @@ -42,7 +42,8 @@ public void checkRelativeInPackage() throws Exception { @Test public void sourceSectionAndName() throws Exception { - var code = """ + var code = + """ main = "Error! """; var src = Source.newBuilder("enso", code, "error_test.enso").build(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeMultiValueTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeMultiValueTest.java index 04edab570896..b4851bf84f64 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeMultiValueTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeMultiValueTest.java @@ -65,11 +65,11 @@ public static Object[][] allPossibleEnsoInterpreterValues() throws Exception { var typeOf = ctxRule.evalModule( """ - from Standard.Base import all + from Standard.Base import all - typ obj = Meta.type_of obj - main = typ - """); + typ obj = Meta.type_of obj + main = typ + """); var data = new ArrayList(); for (var polyValue : g.allValues()) { registerValue(g, typeOf, polyValue, data); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeTest.java index 13415926afcb..d168f89a97e3 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/node/expression/builtin/meta/TypeOfNodeTest.java @@ -34,11 +34,11 @@ public static Object[][] allPossibleEnsoInterpreterValues() throws Exception { var typeOf = ctxRule.evalModule( """ - from Standard.Base import all + from Standard.Base import all - typ obj = Meta.type_of obj - main = typ - """); + typ obj = Meta.type_of obj + main = typ + """); var data = new ArrayList(); for (var v : g.allValues()) { var t = typeOf.execute(v); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ManagedResourceTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ManagedResourceTest.java index 047bcc260e9f..2b49f48e1211 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ManagedResourceTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ManagedResourceTest.java @@ -32,17 +32,17 @@ public static void initCtx() { var ctx = ctxRule.context(); var code = """ - import Standard.Base.Runtime.Managed_Resource.Managed_Resource + import Standard.Base.Runtime.Managed_Resource.Managed_Resource - make_new obj = - Managed_Resource.register obj (_->0) + make_new obj = + Managed_Resource.register obj (_->0) - create_new obj system_resource = - Managed_Resource.register obj (_->0) system_resource + create_new obj system_resource = + Managed_Resource.register obj (_->0) system_resource - get_res ref = ref.with it-> - it - """; + get_res ref = ref.with it-> + it + """; Source src; try { src = Source.newBuilder("enso", code, "gc.enso").build(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ModuleTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ModuleTest.java index 7be5943758cd..f01876c98e1f 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ModuleTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/ModuleTest.java @@ -74,9 +74,14 @@ public void updaterCanNullTheBindings() throws Exception { var ensoContext = ctxRule.ensoContext(); var tFile = ensoContext.getTruffleFile(f); - var code = Source.newBuilder("enso", """ - main = 42 - """, name.toString()).build(); + var code = + Source.newBuilder( + "enso", + """ + main = 42 + """, + name.toString()) + .build(); ctxRule.eval(code); var module = ensoContext.getTopScope().getModule(name.toString()).get().asCompilerModule(); @@ -106,9 +111,14 @@ public void updaterCanNullTheIR() throws Exception { var ensoContext = ctxRule.ensoContext(); var tFile = ensoContext.getTruffleFile(f); - var code = Source.newBuilder("enso", """ - main = 42 - """, name.toString()).build(); + var code = + Source.newBuilder( + "enso", + """ + main = 42 + """, + name.toString()) + .build(); ctxRule.eval(code); var module = ensoContext.getTopScope().getModule(name.toString()).get().asCompilerModule(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/RefTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/RefTest.java index bc7cee27a9e1..e0f64db67e62 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/RefTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/RefTest.java @@ -24,9 +24,9 @@ public static void initCtx() { refType = ctxRule.evalModule( """ - import Standard.Base.Runtime.Ref.Ref - main = Ref - """); + import Standard.Base.Runtime.Ref.Ref + main = Ref + """); } @AfterClass diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/progress/ProgressTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/progress/ProgressTest.java index 6ce7c310d20e..2b3d3b7e21e1 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/progress/ProgressTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/runtime/progress/ProgressTest.java @@ -23,24 +23,24 @@ public ProgressTest() {} public void advanceMultipleTimes() throws Exception { var code = """ - from Standard.Base import Integer, Float - from Standard.Base.Logging import Progress - - geom n:Integer a1:Float q:Float = - Progress.run "geometric sequence" n progress-> - loop i:Integer v:Float acc:Float = - if i == n then acc else - progress.log "Step #"+i.to_text - next = v*q - sum = next+acc - progress.advance - @Tail_Call loop i+1 next sum - - progress.log "About to compute geometric sequence for "+n.to_text - res = loop 1 a1 a1 - progress.log "We have the result "+res.to_text - res - """; + from Standard.Base import Integer, Float + from Standard.Base.Logging import Progress + + geom n:Integer a1:Float q:Float = + Progress.run "geometric sequence" n progress-> + loop i:Integer v:Float acc:Float = + if i == n then acc else + progress.log "Step #"+i.to_text + next = v*q + sum = next+acc + progress.advance + @Tail_Call loop i+1 next sum + + progress.log "About to compute geometric sequence for "+n.to_text + res = loop 1 a1 a1 + progress.log "We have the result "+res.to_text + res + """; var log = LoggerFactory.getLogger("Standard.Base.Logging.Progress"); var geom = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "geom"); @@ -100,18 +100,18 @@ public void useExistingProgressFromJavaViaProgressInterface() throws Exception { private void performExistingProgressFromJavaWith(Object acc) { var code = """ - from Standard.Base import Integer, Float - from Standard.Base.Logging import Progress - - up_to n combine = - Progress.run "from 0 to "+n.to_text n progress-> - loop count_down = - if count_down <= 0 then combine.result else - combine.accumulate count_down progress - @Tail_Call loop count_down-1 - - loop n - """; + from Standard.Base import Integer, Float + from Standard.Base.Logging import Progress + + up_to n combine = + Progress.run "from 0 to "+n.to_text n progress-> + loop count_down = + if count_down <= 0 then combine.result else + combine.accumulate count_down progress + @Tail_Call loop count_down-1 + + loop n + """; var upTo = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "up_to"); var log = LoggerFactory.getLogger("Standard.Base.Logging.Progress"); @@ -139,7 +139,8 @@ private void performExistingProgressFromJavaWith(Object acc) { ADVANCE Progress+1 ADVANCE Progress+1 ADVANCE Progress+1 - ADVANCE Progress+5""", + ADVANCE Progress+5\ + """, txt); } @@ -219,12 +220,12 @@ public String toString() { public void createNewProgressInJava() { var code = """ - from Standard.Base import Integer, Float - from Standard.Base.Logging import Progress + from Standard.Base import Integer, Float + from Standard.Base.Logging import Progress - up_to n host = - host n - """; + up_to n host = + host n + """; var upTo = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "up_to"); var log = LoggerFactory.getLogger("Standard.Base.Logging.Progress"); @@ -258,7 +259,8 @@ public void createNewProgressInJava() { ADVANCE JavaProgress+1 ADVANCE JavaProgress+1 ADVANCE JavaProgress+1 - ADVANCE JavaProgress+5""", + ADVANCE JavaProgress+5\ + """, txt); } } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyOrStaticTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyOrStaticTest.java index 70ab3a3aa105..51ba3ce052e8 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyOrStaticTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyOrStaticTest.java @@ -17,13 +17,13 @@ public class AnyOrStaticTest { public void methodOnModuleAny() throws Exception { var code = """ - from Standard.Base import Any + from Standard.Base import Any - check_is v t = "check of "+v.to_text+" and "+t.to_text - Any.check_is self t = "got to Any for "+self.to_text+" and "+t.to_text + check_is v t = "check of "+v.to_text+" and "+t.to_text + Any.check_is self t = "got to Any for "+self.to_text+" and "+t.to_text - dispatch a b = Checker.check_is a b - """; + dispatch a b = Checker.check_is a b + """; var src = Source.newBuilder(LanguageInfo.ID, code, "Checker.enso").build(); var module = ctxRule.eval(src); @@ -38,15 +38,15 @@ public void methodOnModuleAny() throws Exception { public void methodOnTypeAndAny() throws Exception { var code = """ - from Standard.Base import Any + from Standard.Base import Any - type Type_With_Check - check_is v t = "check of "+v.to_text+" and "+t.to_text + type Type_With_Check + check_is v t = "check of "+v.to_text+" and "+t.to_text - Any.check_is self t = "got to Any for "+self.to_text+" and "+t.to_text + Any.check_is self t = "got to Any for "+self.to_text+" and "+t.to_text - dispatch a = Type_With_Check.check_is a - """; + dispatch a = Type_With_Check.check_is a + """; var src = Source.newBuilder(LanguageInfo.ID, code, "Typer.enso").build(); var module = ctxRule.eval(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyToTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyToTest.java index a1f6264b82d5..38eca4fd6b8b 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyToTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AnyToTest.java @@ -21,16 +21,16 @@ public void multiValueToInteger() throws Exception { new Type[] {ensoCtx.getBuiltins().number().getInteger(), ensoCtx.getBuiltins().text()}; var code = """ - from Standard.Base import all + from Standard.Base import all - private eq a b = a == b + private eq a b = a == b - conv style v = case style of - 0 -> v.to Integer - 1 -> v:Integer - 99 -> eq + conv style v = case style of + 0 -> v.to Integer + 1 -> v:Integer + 99 -> eq - """; + """; var conv = ctxRule.evalModule(Source.newBuilder("enso", code, "conv.enso").build(), "conv"); var both = EnsoMultiValue.NewNode.getUncached() @@ -61,16 +61,16 @@ private void multiValueToText(int dispatchLength) throws Exception { new Type[] {ensoCtx.getBuiltins().number().getInteger(), ensoCtx.getBuiltins().text()}; var code = """ - from Standard.Base import all + from Standard.Base import all - private eq a b = a == b + private eq a b = a == b - conv style:Integer v = case style of - 2 -> v.to Text - 3 -> v:Text - 99 -> eq + conv style:Integer v = case style of + 2 -> v.to Text + 3 -> v:Text + 99 -> eq - """; + """; var conv = ctxRule.evalModule(Source.newBuilder("enso", code, "conv.enso").build(), "conv"); var both = EnsoMultiValue.NewNode.getUncached() diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AtomConstructorTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AtomConstructorTest.java index 3ed29af5f758..db0c748ef7e2 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AtomConstructorTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AtomConstructorTest.java @@ -27,7 +27,8 @@ public AtomConstructorTest() {} @Test public void testGetUncached() { - var code = """ + var code = + """ type NoPrime A a b c """; @@ -46,7 +47,8 @@ public void testGetUncached() { @Test public void testAtomNewInstanceNode() { - var code = """ + var code = + """ type X A a b c """; diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AutoscopedConstructorTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AutoscopedConstructorTest.java index 43460dfa999c..34ecc96e18cf 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AutoscopedConstructorTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/AutoscopedConstructorTest.java @@ -265,16 +265,16 @@ public void wrongConstructorNameYieldsTypeError() { public void simpleAnyCheck() { var code = """ - import Standard.Base.Any.Any + import Standard.Base.Any.Any - type A - Typed x:Any + type A + Typed x:Any - t = ..Typed ..My_Other - materialize v:A = v + t = ..Typed ..My_Other + materialize v:A = v - create = materialize t - """; + create = materialize t + """; var create = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "create"); @@ -286,16 +286,16 @@ public void simpleAnyCheck() { public void simpleAnyOrACheck() { var code = """ - import Standard.Base.Any.Any + import Standard.Base.Any.Any - type A - Typed (x:Any|A) + type A + Typed (x:Any|A) - t = ..Typed ..My_Other - materialize v:A = v + t = ..Typed ..My_Other + materialize v:A = v - create = materialize t - """; + create = materialize t + """; var create = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "create"); @@ -307,16 +307,16 @@ public void simpleAnyOrACheck() { public void intersectionAnyOrACheck() { var code = """ - import Standard.Base.Any.Any + import Standard.Base.Any.Any - type A - Typed (x:Any&A) + type A + Typed (x:Any&A) - t = ..Typed ..My_Other - materialize v:A = v + t = ..Typed ..My_Other + materialize v:A = v - create = materialize t - """; + create = materialize t + """; try { var create = diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BigNumberTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BigNumberTest.java index 6d0d67a1ad9c..ff89cd282f09 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BigNumberTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BigNumberTest.java @@ -24,15 +24,15 @@ public class BigNumberTest { public void evaluation() throws Exception { final String code = """ - import Standard.Base.Data.Vector.Builder - from Standard.Base.Data.Vector import Vector - - powers n = - go x v b = if x > n then b.to_vector else - b.append v - @Tail_Call go x+1 v*3 b - go 1 1 Builder.new - """; + import Standard.Base.Data.Vector.Builder + from Standard.Base.Data.Vector import Vector + + powers n = + go x v b = if x > n then b.to_vector else + b.append v + @Tail_Call go x+1 v*3 b + go 1 1 Builder.new + """; var powers = evalCode(code, "powers"); var vec = powers.execute(200); @@ -81,18 +81,18 @@ private Value evalCode(final String code, final String methodName) throws URISyn public void averageOfMixedArrayOverNumber() throws Exception { var code = """ - import Standard.Base.Data.Vector.Builder - from Standard.Base.Data.Vector import Vector - polyglot java import org.enso.example.TestClass - - powers n = - go x v b = if x > n then b.to_vector else - b.append v - @Tail_Call go x+1 v*2 b - go 1 1 Builder.new - - avg n = TestClass.numberArrayAverage (powers n) - """; + import Standard.Base.Data.Vector.Builder + from Standard.Base.Data.Vector import Vector + polyglot java import org.enso.example.TestClass + + powers n = + go x v b = if x > n then b.to_vector else + b.append v + @Tail_Call go x+1 v*2 b + go 1 1 Builder.new + + avg n = TestClass.numberArrayAverage (powers n) + """; var fn = evalCode(code, "avg"); var avg = fn.execute(200); @@ -106,19 +106,19 @@ public void averageOfMixedArrayOverNumber() throws Exception { public void averageOfMixedArrayOverBigInteger() throws Exception { var code = """ - import Standard.Base.Data.Vector.Builder - from Standard.Base.Data.Vector import Vector - import Standard.Base.Data.Numbers - polyglot java import org.enso.example.TestClass - - powers n = - go x v b = if x > n then b.to_vector else - b.append v - @Tail_Call go x+1 v*2 b - go 1 1 Builder.new - - avg n = TestClass.exactArrayAverage (powers n) - """; + import Standard.Base.Data.Vector.Builder + from Standard.Base.Data.Vector import Vector + import Standard.Base.Data.Numbers + polyglot java import org.enso.example.TestClass + + powers n = + go x v b = if x > n then b.to_vector else + b.append v + @Tail_Call go x+1 v*2 b + go 1 1 Builder.new + + avg n = TestClass.exactArrayAverage (powers n) + """; var fn = evalCode(code, "avg"); var avg = fn.execute(200); @@ -129,10 +129,11 @@ public void averageOfMixedArrayOverBigInteger() throws Exception { } private Value assertMul(Object a, Object b) throws URISyntaxException { - var code = """ - import Standard.Base.Data.Numbers - mul a b = a * b - """; + var code = + """ + import Standard.Base.Data.Numbers + mul a b = a * b + """; var fn = evalCode(code, "mul"); return fn.execute(a, b); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpFloatTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpFloatTest.java index df4fd09deec2..2f4b4059d63e 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpFloatTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpFloatTest.java @@ -102,9 +102,11 @@ public BinaryOpFloatTest(String operation, double n1, double n2) { @Test public void verifyOperationOnForeignObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = execute(fn, n1, n2); @@ -117,9 +119,11 @@ public void verifyOperationOnForeignObject() { @Test public void verifyOperationWithConvertibleObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = fn.execute(n1, n2); @@ -137,9 +141,11 @@ public void verifyOperationWithConvertibleObject() { @Test public void verifyOperationOnConvertibleObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = fn.execute(n1, n2); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpIntegerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpIntegerTest.java index 980d6d404777..0de6338cb410 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpIntegerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/BinaryOpIntegerTest.java @@ -122,9 +122,11 @@ public BinaryOpIntegerTest(String operation, long n1, long n2) { @Test public void verifyOperationOnForeignObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = fn.execute(n1, n2); @@ -137,9 +139,11 @@ public void verifyOperationOnForeignObject() { @Test public void verifyOperationWithConvertibleObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = fn.execute(n1, n2); @@ -159,9 +163,11 @@ public void verifyOperationWithConvertibleObject() { @Test public void verifyOperationOnConvertibleObject() { - var code = """ - fn a b = a{op} b - """.replace("{op}", operation); + var code = + """ + fn a b = a{op} b + """ + .replace("{op}", operation); var fn = ctxRule.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); var r1 = fn.execute(n1, n2); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/CaseOfTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/CaseOfTest.java index 7c651ff3eb8e..c49769374e1f 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/CaseOfTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/CaseOfTest.java @@ -40,13 +40,13 @@ public void caseOfMultiValueBoolean() { private void doCaseOfBoolean(Object t, Object f) { var code = """ - from Standard.Base import True, False + from Standard.Base import True, False - choose v = case v of - True -> 1 - False -> 2 - _ -> 3 - """; + choose v = case v of + True -> 1 + False -> 2 + _ -> 3 + """; var choose = ctxRule.evalModule(code, "choose.enso", "choose"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ConversionMethodTests.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ConversionMethodTests.java index d0d688bf2955..813564e4e143 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ConversionMethodTests.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ConversionMethodTests.java @@ -31,17 +31,17 @@ private String getStdOut() { public void testSimpleConversion() { String src = """ - type Foo - Mk_Foo foo - type Bar - Mk_Bar bar - type Baz - Mk_Baz baz + type Foo + Mk_Foo foo + type Bar + Mk_Bar bar + type Baz + Mk_Baz baz - Foo.from (that:Bar) = Foo.Mk_Foo that.bar - Foo.from (that:Baz) = Foo.Mk_Foo that.baz + Foo.from (that:Bar) = Foo.Mk_Foo that.bar + Foo.from (that:Baz) = Foo.Mk_Foo that.baz - main = (Foo.from (Baz.Mk_Baz 10)).foo + (Foo.from (Bar.Mk_Bar 20)).foo + main = (Foo.from (Baz.Mk_Baz 10)).foo + (Foo.from (Bar.Mk_Bar 20)).foo """; Value res = ctx.evalModule(src); assertEquals(30, res.asInt()); @@ -51,18 +51,18 @@ public void testSimpleConversion() { public void testDispatchOnHostMap() { String src = """ - polyglot java import java.util.Map as Java_Map - import Standard.Base.Data.Dictionary.Dictionary + polyglot java import java.util.Map as Java_Map + import Standard.Base.Data.Dictionary.Dictionary - type Foo - Mk_Foo data + type Foo + Mk_Foo data - Foo.from (that:Dictionary) = Foo.Mk_Foo that + Foo.from (that:Dictionary) = Foo.Mk_Foo that - main = - jmap = Java_Map.of "A" 1 "B" 2 "C" 3 - Foo.from jmap . data . size - """; + main = + jmap = Java_Map.of "A" 1 "B" 2 "C" 3 + Foo.from jmap . data . size + """; Value res = ctx.evalModule(src); assertEquals(3, res.asInt()); } @@ -71,22 +71,22 @@ public void testDispatchOnHostMap() { public void testDispatchOnJSMap() { String src = """ - import Standard.Base.Data.Dictionary.Dictionary + import Standard.Base.Data.Dictionary.Dictionary - foreign js js_map = ''' - let m = new Map() - m.set("A", 1) - m.set("B", 2) - return m + foreign js js_map = ''' + let m = new Map() + m.set("A", 1) + m.set("B", 2) + return m - type Foo - Mk_Foo data + type Foo + Mk_Foo data - Foo.from (that:Dictionary) = Foo.Mk_Foo that + Foo.from (that:Dictionary) = Foo.Mk_Foo that - main = - Foo.from js_map . data . size - """; + main = + Foo.from js_map . data . size + """; Value res = ctx.evalModule(src); assertEquals(2, res.asInt()); } @@ -95,19 +95,19 @@ public void testDispatchOnJSMap() { public void testDispatchOnJSDateTime() { String src = """ - import Standard.Base.Data.Time.Date_Time.Date_Time + import Standard.Base.Data.Time.Date_Time.Date_Time - foreign js js_date year month day hour minute second nanosecond = ''' - return new Date(year, month - 1, day, hour, minute, second, nanosecond / 1000000); + foreign js js_date year month day hour minute second nanosecond = ''' + return new Date(year, month - 1, day, hour, minute, second, nanosecond / 1000000); - type Foo - Mk_Foo data + type Foo + Mk_Foo data - Foo.from (that:Date_Time) = Foo.Mk_Foo that + Foo.from (that:Date_Time) = Foo.Mk_Foo that - main = - Foo.from (js_date 2023 2 7 23 59 0 10) . data . day - """; + main = + Foo.from (js_date 2023 2 7 23 59 0 10) . data . day + """; Value res = ctx.evalModule(src); assertEquals(7, res.asInt()); } @@ -116,16 +116,16 @@ public void testDispatchOnJSDateTime() { public void testAmbiguousConversionStrictUnused() { String src = """ - type Foo - Mk_Foo data - type Bar - Mk_Bar x + type Foo + Mk_Foo data + type Bar + Mk_Bar x - Foo.from (that:Bar) = Foo.Mk_Foo that.x+100 - Foo.from (that:Bar) = Foo.Mk_Foo that.x+1000 + Foo.from (that:Bar) = Foo.Mk_Foo that.x+100 + Foo.from (that:Bar) = Foo.Mk_Foo that.x+1000 - main = 42 - """; + main = 42 + """; try { Value res = ctx.evalModule(src); fail("Expected an exception, but got " + res); @@ -143,25 +143,25 @@ public void testAmbiguousConversionStrictUnused() { public void testNoConversionWhenMultiValueMatches() { String src = """ - from Standard.Base import Any, Integer, Meta, Runtime + from Standard.Base import Any, Integer, Meta, Runtime - type Foo - F n - type Bar - B n + type Foo + F n + type Bar + B n - Foo.from (that:Integer) = Foo.F 100*that - Bar.from (that:Integer) = Bar.B 1000*that + Foo.from (that:Integer) = Foo.F 100*that + Bar.from (that:Integer) = Bar.B 1000*that - main = - a = 42 : (Foo&Bar) - Runtime.assert <| Meta.is_a a Foo - Runtime.assert <| Meta.is_a a Bar - b = Bar.from a - f = Foo.from a - [a, b, f] + main = + a = 42 : (Foo&Bar) + Runtime.assert <| Meta.is_a a Foo + Runtime.assert <| Meta.is_a a Bar + b = Bar.from a + f = Foo.from a + [a, b, f] - """; + """; var arr = ctx.evalModule(src); assertTrue("It is array", arr.hasArrayElements()); assertEquals("Three elements", 3, arr.getArraySize()); @@ -181,29 +181,29 @@ public void testNoConversionWhenMultiValueMatches() { public void testNoConversionWhenMultiValueMatchesTwoOfThee() { String src = """ - from Standard.Base import Any, Integer, Meta, Runtime - - type Foo - F n - type Bar - B n - type Car - C n - - Foo.from (that:Integer) = Foo.F 100*that - Bar.from (that:Integer) = Bar.B 1000*that - Car.from (that:Integer) = Car.C 10000*that - - main = - a = 42 : (Foo&Bar&Car) - Runtime.assert <| Meta.is_a a Foo - Runtime.assert <| Meta.is_a a Bar - Runtime.assert <| Meta.is_a a Car - cb = a : (Car&Bar) - fc = a : (Foo&Car) - [a, cb, fc] - - """; + from Standard.Base import Any, Integer, Meta, Runtime + + type Foo + F n + type Bar + B n + type Car + C n + + Foo.from (that:Integer) = Foo.F 100*that + Bar.from (that:Integer) = Bar.B 1000*that + Car.from (that:Integer) = Car.C 10000*that + + main = + a = 42 : (Foo&Bar&Car) + Runtime.assert <| Meta.is_a a Foo + Runtime.assert <| Meta.is_a a Bar + Runtime.assert <| Meta.is_a a Car + cb = a : (Car&Bar) + fc = a : (Foo&Car) + [a, cb, fc] + + """; var arr = ctx.evalModule(src); assertTrue("It is array", arr.hasArrayElements()); assertEquals("Three elements", 3, arr.getArraySize()); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java index 7e29ae63a082..40a18442bb57 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java @@ -155,17 +155,17 @@ public void recursiveFactorialCall() { final Value facFn = createEnsoMethod( """ - from Standard.Base import all + from Standard.Base import all - fac : Number -> Number - fac n = - facacc : Number -> Number -> Number - facacc n accumulator = - stop = n <= 1 - if stop then accumulator else @Tail_Call facacc n-1 n*accumulator + fac : Number -> Number + fac n = + facacc : Number -> Number -> Number + facacc n accumulator = + stop = n <= 1 + if stop then accumulator else @Tail_Call facacc n-1 n*accumulator - facacc n 1 - """, + facacc n 1 + """, "fac"); final var values = new TreeSet(); @@ -195,14 +195,14 @@ public void callerVariablesAreVisibleOnPreviousStackFrame() { Value fooFunc = createEnsoMethod( """ - bar arg_bar = - loc_bar = arg_bar + 1 - loc_bar - - foo x = - loc_foo = 1 - bar loc_foo - """, + bar arg_bar = + loc_bar = arg_bar + 1 + loc_bar + + foo x = + loc_foo = 1 + bar loc_foo + """, "foo"); try (DebuggerSession session = @@ -210,13 +210,13 @@ public void callerVariablesAreVisibleOnPreviousStackFrame() { (SuspendedEvent event) -> { // TODO[PM]: This is a workaround for proper breakpoints, which do not work atm. switch (event.getSourceSection().getCharacters().toString().strip()) { - // In method "foo" + // In method "foo" case "bar loc_foo" -> { List stackFrames = getStackFramesFromEvent(event); Assert.assertEquals(1, stackFrames.size()); expectStackFrame(stackFrames.get(0), Map.of("x", "42", "loc_foo", "1")); } - // In method "bar" called from "foo" + // In method "bar" called from "foo" case "loc_bar" -> { List stackFrames = getStackFramesFromEvent(event); @@ -240,16 +240,16 @@ public void testHostValues() { Value fooFunc = createEnsoMethod( """ - polyglot java import java.nio.file.Path - polyglot java import java.util.ArrayList - - foo x = - path = Path.of 'blaaaaa' - list = ArrayList.new - list.add 10 - list.add 20 - tmp = 42 - """, + polyglot java import java.nio.file.Path + polyglot java import java.util.ArrayList + + foo x = + path = Path.of 'blaaaaa' + list = ArrayList.new + list.add 10 + list.add 20 + tmp = 42 + """, "foo"); try (DebuggerSession session = @@ -287,51 +287,51 @@ public void hostValueIsTreatedAsItsEnsoCounterpart() { Value fooFunc = createEnsoMethod( """ - from Standard.Base import Date, Date_Time, Dictionary - polyglot java import java.lang.String - polyglot java import java.util.List as JList - polyglot java import java.util.Map as JMap - - foreign js js_date = ''' - return new Date(); - - foreign js js_str = ''' - return "Hello_World"; - - foreign js js_list = ''' - return [1, 2, 3]; - - foreign js js_map = ''' - let m = new Map(); - m.set('A', 1); - m.set('B', 2); - return m; - - foreign python py_list = ''' - return [1, 2, 3] - - foreign python py_dict = ''' - return {'A': 1, 'B': 2} - - foo _ = - d_enso = Date.new 2024 12 15 - d_java = Date.parse "2024-12-15" - dt_enso = Date_Time.now - dt_java = Date_Time.parse "2020-05-06 04:30:20" "yyyy-MM-dd HH:mm:ss" - dt_js = js_date - str_enso = "Hello_World" - str_js = js_str - str_java = String.new "Hello_World" - list_enso = [1, 2, 3] - list_js = js_list - list_py = py_list - list_java = JList.of 1 2 3 - dict_enso = Dictionary.from_vector [["A", 1], ["B", 2]] - dict_js = js_map - dict_py = py_dict - dict_java = JMap.of "A" 1 "B" 2 - end = 42 - """, + from Standard.Base import Date, Date_Time, Dictionary + polyglot java import java.lang.String + polyglot java import java.util.List as JList + polyglot java import java.util.Map as JMap + + foreign js js_date = ''' + return new Date(); + + foreign js js_str = ''' + return "Hello_World"; + + foreign js js_list = ''' + return [1, 2, 3]; + + foreign js js_map = ''' + let m = new Map(); + m.set('A', 1); + m.set('B', 2); + return m; + + foreign python py_list = ''' + return [1, 2, 3] + + foreign python py_dict = ''' + return {'A': 1, 'B': 2} + + foo _ = + d_enso = Date.new 2024 12 15 + d_java = Date.parse "2024-12-15" + dt_enso = Date_Time.now + dt_java = Date_Time.parse "2020-05-06 04:30:20" "yyyy-MM-dd HH:mm:ss" + dt_js = js_date + str_enso = "Hello_World" + str_js = js_str + str_java = String.new "Hello_World" + list_enso = [1, 2, 3] + list_js = js_list + list_py = py_list + list_java = JList.of 1 2 3 + dict_enso = Dictionary.from_vector [["A", 1], ["B", 2]] + dict_js = js_map + dict_py = py_dict + dict_java = JMap.of "A" 1 "B" 2 + end = 42 + """, "foo"); try (DebuggerSession session = @@ -401,21 +401,21 @@ public void testHostValueAsAtomField() { Value fooFunc = createEnsoMethod( """ - import Standard.Base.Internal.Array_Like_Helpers - from Standard.Base import Any - from Standard.Base import Integer + import Standard.Base.Internal.Array_Like_Helpers + from Standard.Base import Any + from Standard.Base import Integer - new_vector_builder : Integer -> Any - new_vector_builder capacity = @Builtin_Method "Array_Like_Helpers.new_vector_builder" + new_vector_builder : Integer -> Any + new_vector_builder capacity = @Builtin_Method "Array_Like_Helpers.new_vector_builder" - type Builder - Value java_builder + type Builder + Value java_builder - foo x = - java_builder = new_vector_builder 1 - builder = Builder.Value java_builder - end = 42 - """, + foo x = + java_builder = new_vector_builder 1 + builder = Builder.Value java_builder + end = 42 + """, "foo"); try (DebuggerSession session = @@ -440,13 +440,13 @@ public void testEvaluateExpression() { Value fooFunc = createEnsoMethod( """ - polyglot java import java.nio.file.Path + polyglot java import java.nio.file.Path - foo x = - a = 10 - b = 20 - tmp = 42 - """, + foo x = + a = 10 + b = 20 + tmp = 42 + """, "foo"); try (DebuggerSession session = @@ -473,13 +473,13 @@ public void testEvaluateExpressionInDebugBreakpoint() { createEnsoMethod( """ - import Standard.Base.Runtime.Debug + import Standard.Base.Runtime.Debug - foo x = - a = 6 - b = 7 - Debug.breakpoint - """, + foo x = + a = 6 + b = 7 + Debug.breakpoint + """, "foo"); int[] res = {0}; @@ -507,12 +507,12 @@ public void testRewriteLocalVariable() { Value fooFunc = createEnsoMethod( """ - foo x = - a = 10 - b = 20 - tmp = a + b - end = 42 - """, + foo x = + a = 10 + b = 20 + tmp = a + b + end = 42 + """, "foo"); try (DebuggerSession session = @@ -547,15 +547,15 @@ public void testRewriteVariableInCallerStackFrame() { Value fooFunc = createEnsoMethod( """ - bar = - loc_bar = 42 - - foo x = - a = 10 # Will get modified to 1 - b = 20 # Will get modified to 2 - bar - a + b - """, + bar = + loc_bar = 42 + + foo x = + a = 10 # Will get modified to 1 + b = 20 # Will get modified to 2 + bar + a + b + """, "foo"); try (DebuggerSession session = @@ -626,13 +626,13 @@ public void testAtomFieldsAreReadable() { var fooFunc = createEnsoMethod( """ - type My_Type - Cons field_1 field_2 + type My_Type + Cons field_1 field_2 - foo x = - obj = My_Type.Cons 1 2 - obj - """, + foo x = + obj = My_Type.Cons 1 2 + obj + """, "foo"); try (DebuggerSession session = debugger.startSession( @@ -664,14 +664,14 @@ public void testAtomFieldAreReadable_MultipleConstructors() { var fooFunc = createEnsoMethod( """ - type My_Type - Cons_1 f1 f2 - Cons_2 g1 g2 g3 - - foo x = - obj = My_Type.Cons_1 1 2 - obj - """, + type My_Type + Cons_1 f1 f2 + Cons_2 g1 g2 g3 + + foo x = + obj = My_Type.Cons_1 1 2 + obj + """, "foo"); try (DebuggerSession session = debugger.startSession( @@ -767,14 +767,14 @@ public void testSteppingOver() { Source src = createEnsoSource( """ - baz x = x # 1 - bar x = # 2 - ret = baz x # 3 - ret # 4 - foo x = # 5 - bar 42 # 6 - end = 0 # 7 - """); + baz x = x # 1 + bar x = # 2 + ret = baz x # 3 + ret # 4 + foo x = # 5 + bar 42 # 6 + end = 0 # 7 + """); List expectedLineNumbers = List.of(5, 6, 7); Queue steps = createStepOverEvents(expectedLineNumbers.size()); testStepping(src, "foo", new Object[] {0}, steps, expectedLineNumbers); @@ -789,19 +789,19 @@ public void testSteppingOverUseStdLib() { Source src = createEnsoSource( """ - from Standard.Base import Vector - import Standard.Base.Data.Vector.Builder + from Standard.Base import Vector + import Standard.Base.Data.Vector.Builder - bar vec num_elems = - vec.slice 0 num_elems + bar vec num_elems = + vec.slice 0 num_elems - foo x = - vec_builder = Builder.new - vec_builder.append 1 - vec_builder.append 2 - vec = bar (vec_builder.to_vector) (vec_builder.to_vector.length - 1) - end = 0 - """); + foo x = + vec_builder = Builder.new + vec_builder.append 1 + vec_builder.append 2 + vec = bar (vec_builder.to_vector) (vec_builder.to_vector.length - 1) + end = 0 + """); List expectedLines = List.of( @@ -821,12 +821,12 @@ public void testSteppingInto() { Source src = createEnsoSource( """ - baz x = x # 1 - bar x = baz x # 2 - foo x = # 3 - bar 42 # 4 - end = 0 # 5 - """); + baz x = x # 1 + bar x = baz x # 2 + foo x = # 3 + bar 42 # 4 + end = 0 # 5 + """); List expectedLineNumbers = List.of(3, 4, 2, 1, 2, 4, 5); Queue steps = new ArrayDeque<>( @@ -840,12 +840,12 @@ public void testSteppingIntoMoreExpressionsOneLine() { Source src = createEnsoSource( """ - baz x = x # 1 - bar x = x # 2 - foo x = # 3 - bar (baz x) # 4 - end = 0 # 5 - """); + baz x = x # 1 + bar x = x # 2 + foo x = # 3 + bar (baz x) # 4 + end = 0 # 5 + """); List expectedLineNumbers = List.of(3, 4, 1, 4, 2, 4, 5); Queue steps = new ArrayDeque<>( @@ -858,20 +858,20 @@ public void testEvaluateLazyField() { var fooFunc = createEnsoMethod( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type Generator - Value n ~next + type Generator + Value n ~next - natural = - gen n = Generator.Value n (gen n+1) - gen 2 + natural = + gen n = Generator.Value n (gen n+1) + gen 2 - foo x = - two = natural - three = two.next - end = 0 - """, + foo x = + two = natural + three = two.next + end = 0 + """, "foo"); try (DebuggerSession session = debugger.startSession( @@ -899,10 +899,10 @@ public void breakInMeta() { Value fooFunc = createEnsoMethod( """ - from Standard.Base import Meta - foo x = - Meta.meta x - """, + from Standard.Base import Meta + foo x = + Meta.meta x + """, "foo"); var interceptedKind = new int[] {-1}; diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DiagnosticFormatterTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DiagnosticFormatterTest.java index c136b201ea6b..9c120467b0ea 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DiagnosticFormatterTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/DiagnosticFormatterTest.java @@ -39,7 +39,8 @@ public void resetOut() { """ tmp_test:1:8: error: The name `foo` could not be found. 1 | main = foo - | ^~~"""; + | ^~~\ + """; private Pair compileExample() throws IOException { var code = "main = foo"; diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EnsoMultiValueTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EnsoMultiValueTest.java index a2e18869bf8f..11a946668098 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EnsoMultiValueTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EnsoMultiValueTest.java @@ -25,34 +25,34 @@ public class EnsoMultiValueTest { public void keepIdentityOfAandB() throws Exception { var types = """ - from project.PrivateConversion import all - type A - A_Ctor x + from project.PrivateConversion import all + type A + A_Ctor x - id_a self -> A = self - type B - B_Ctor x + id_a self -> A = self + type B + B_Ctor x - ab = - a = A.A_Ctor 1 - (a : A & B) - """; + ab = + a = A.A_Ctor 1 + (a : A & B) + """; var privateConversion = """ - from project.Types import all + from project.Types import all - B.from (that : A) = B.B_Ctor that - """; + B.from (that : A) = B.B_Ctor that + """; var main = """ - from project.Types import all + from project.Types import all - main = - v = ab.id_a - [v.to_text, (v:A).to_text, (v:B).to_text] - """; + main = + v = ab.id_a + [v.to_text, (v:A).to_text, (v:B).to_text] + """; var prjDir = dir.newFolder(); var sources = new HashSet(); @@ -85,26 +85,26 @@ public void sameFieldAccessBandA() { private void sameFieldAccess(String cast) { var code = """ - type A - A_Ctor x y + type A + A_Ctor x y - x_from_a self = self.x + x_from_a self = self.x - type B - B_Ctor x y + type B + B_Ctor x y - x_from_b self = self.x + x_from_b self = self.x - B.from (that : A) = B.B_Ctor "B" that.y + B.from (that : A) = B.B_Ctor "B" that.y - pair = - a = A.A_Ctor "A" 1 - both = (a : $cast) + pair = + a = A.A_Ctor "A" 1 + both = (a : $cast) - v_a = both.x_from_a - v_b = both.x_from_b - [v_a, v_b] - """ + v_a = both.x_from_a + v_b = both.x_from_b + [v_a, v_b] + """ .replace("$cast", cast); var pair = ctxRule.evalModule(code, "fields.enso", "pair"); @@ -118,26 +118,26 @@ private void sameFieldAccess(String cast) { public void trippleCastConfusion() { var code = """ - type A - A_Ctor x - type B - B_Ctor x - type C - C_Ctor x - - B.from (that : A) = B.B_Ctor that - C.from (that:B) = C.C_Ctor that - - texts = - a = A.A_Ctor 1 - ab = (a : A & B) - abc = ab:(A & B & C) - c = abc:C - - text_a = (c:A).to_text - text_b = (c:B).to_text - [text_a, text_b, c.to_text] - """; + type A + A_Ctor x + type B + B_Ctor x + type C + C_Ctor x + + B.from (that : A) = B.B_Ctor that + C.from (that:B) = C.C_Ctor that + + texts = + a = A.A_Ctor 1 + ab = (a : A & B) + abc = ab:(A & B & C) + c = abc:C + + text_a = (c:A).to_text + text_b = (c:B).to_text + [text_a, text_b, c.to_text] + """; var tripple = ctxRule.evalModule(code, "tripple.enso", "texts"); var texts = tripple.as(new TypeLiteral>() {}); @@ -151,21 +151,21 @@ public void trippleCastConfusion() { public void dataflowErrorPassingThroughMultiChecks() { var code = """ - from Standard.Base import Error + from Standard.Base import Error - type A - type B - type My_Error - Error msg + type A + type B + type My_Error + Error msg - make -> A & B = - Error.throw (My_Error.Error "msg") + make -> A & B = + Error.throw (My_Error.Error "msg") - foo = - a = make - fun (x : A & B) = x - fun a - """; + foo = + a = make + fun (x : A & B) = x + fun a + """; var foo = ctxRule.evalModule(code, "dataflow.enso", "foo"); assertTrue("Returns a dataflow error", foo.isException()); @@ -176,48 +176,48 @@ public void dataflowErrorPassingThroughMultiChecks() { public void makeAbx13272() throws Exception { var types = """ - from project.PrivateConversion import all - type A - A_Ctor x + from project.PrivateConversion import all + type A + A_Ctor x - a_method self = "A method" - type B - B_Ctor x + a_method self = "A method" + type B + B_Ctor x - b_method self = "B method" + b_method self = "B method" - type X - X_Ctor x + type X + X_Ctor x - x_method self = "X method" + x_method self = "X method" - make_abx -> A & B & X = - a = A.A_Ctor 1 - # Relies on the hidden conversions - (a : A & B & X) - """; + make_abx -> A & B & X = + a = A.A_Ctor 1 + # Relies on the hidden conversions + (a : A & B & X) + """; var privateConversion = """ - from project.Types import all + from project.Types import all - B.from (that : A) = B.B_Ctor that - X.from (that : A) -> X = - X.X_Ctor that - """; + B.from (that : A) = B.B_Ctor that + X.from (that : A) -> X = + X.X_Ctor that + """; var main = """ - from project.Types import all - - main = - abx = make_abx - # X is hidden in A & B - ab = (abx : A & B) - # but should still be possible to uncover it - x = (ab:X) - [abx, ab, x] - """; + from project.Types import all + + main = + abx = make_abx + # X is hidden in A & B + ab = (abx : A & B) + # but should still be possible to uncover it + x = (ab:X) + [abx, ab, x] + """; var prjDir = dir.newFolder(); var sources = new HashSet(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsConversionsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsConversionsTest.java index 45a41ade84e3..4d423d2b9a7a 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsConversionsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsConversionsTest.java @@ -19,16 +19,16 @@ public void testBasicInequalities() { ctxRule .evalModule( """ - from Standard.Base import all + from Standard.Base import all - Text.from (that:Number) = that.to_text + Text.from (that:Number) = that.to_text - main = - r0 = "4"+"2" == "42" - r1 = 42 == "42" - r2 = "42" == 42 - [ r0, r1, r2 ] - """) + main = + r0 = "4"+"2" == "42" + r1 = 42 == "42" + r2 = "42" == 42 + [ r0, r1, r2 ] + """) .as(List.class); assertTrue("strings are equal: " + results, (boolean) results.get(0)); @@ -80,12 +80,12 @@ public void testDifferentComparators() { gen.numComparator = false; gen.extraBlock = """ - type Second_Comparator - compare a:Num b:Num = Num_Comparator.compare a b - hash a:Num = Num_Comparator.hash a + type Second_Comparator + compare a:Num b:Num = Num_Comparator.compare a b + hash a:Num = Num_Comparator.hash a - Comparable.from (that:Num) = Comparable.new that Second_Comparator - """; + Comparable.from (that:Num) = Comparable.new that Second_Comparator + """; assertFalse("Num.Value not equal to Integer: ", gen.evaluate()); } @@ -132,31 +132,31 @@ boolean evaluate() { !intNumConversion ? "" : """ - Num.from (that:Integer) = Num.Value that - """; + Num.from (that:Integer) = Num.Value that + """; var block2 = !numComparator ? "" : """ - Comparable.from (that:Num) = Comparable.new that Num_Comparator - """; + Comparable.from (that:Num) = Comparable.new that Num_Comparator + """; var block3 = !intComparator ? "" : """ - Comparable.from (that:Integer) = Comparable.new that Num_Comparator - """; + Comparable.from (that:Integer) = Comparable.new that Num_Comparator + """; var mainBlock = """ - main = - num42 = Num.Value 42 + main = + num42 = Num.Value 42 - r0 = 42 == num42 - r0 - """; + r0 = 42 == num42 + r0 + """; var res = ctxRule.evalModule(block0 + block1 + block2 + block3 + mainBlock + extraBlock); return res.asBoolean(); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsMultiValueTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsMultiValueTest.java index e0348a48f6ed..24265a0c77c6 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsMultiValueTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsMultiValueTest.java @@ -159,58 +159,58 @@ public void testEqualityIntegerAndMultiValueWithConversion() throws Exception { private void assertEqualityIntegerWithConversion(String complexNew) throws Exception { var code = """ - import Standard.Base.Data.Numbers.Float - import Standard.Base.Data.Numbers.Number - import Standard.Base.Data.Ordering.Comparable - import Standard.Base.Data.Ordering.Ordering - import Standard.Base.Nothing - import Standard.Base.Error.Error - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - - ## Sample definition of a complex number with conversions - from Number and implementation of a comparator. - type Complex - private Value re:Float im:Float - - new re=0:Float im=0:Float -> Complex = - c = Complex.Value re 0 - if im != 0 then c:Complex else - ${complexNew} - - + self (that:Complex) = Complex.new self.re+that.re self.im+that.im - - < self (that:Complex) = Complex_Comparator.compare self that == Ordering.Less - > self (that:Complex) = Complex_Comparator.compare self that == Ordering.Greater - >= self (that:Complex) = - ordering = Complex_Comparator.compare self that - ordering == Ordering.Greater || ordering == Ordering.Equal - <= self (that:Complex) = - ordering = Complex_Comparator.compare self that - ordering == Ordering.Less || ordering == Ordering.Equal - - Complex.from (that:Number) = Complex.new that - - - Comparable.from (that:Complex) = Comparable.new that Complex_Comparator - Comparable.from (that:Number) = Comparable.new that Complex_Comparator - - type Complex_Comparator - compare x:Complex y:Complex = if x.re==y.re && x.im==y.im then Ordering.Equal else - if x.im==0 && y.im==0 then Ordering.compare x.re y.re else - Nothing - hash x:Complex = if x.im == 0 then Ordering.hash x.re else - 7*x.re + 11*x.im - - ## uses the explicit conversion defined in this private module - Complex.as_complex_and_float self = - self : Complex&Float - - ## explicit "conversion" of `Complex` to `Float` in a private module - used in `as_complex_and_float` - Float.from (that:Complex) = - if that.im == 0 then that.re else - Error.throw <| Illegal_Argument.Error "Cannot convert Complex with imaginary part to Float" - """ + import Standard.Base.Data.Numbers.Float + import Standard.Base.Data.Numbers.Number + import Standard.Base.Data.Ordering.Comparable + import Standard.Base.Data.Ordering.Ordering + import Standard.Base.Nothing + import Standard.Base.Error.Error + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + + ## Sample definition of a complex number with conversions + from Number and implementation of a comparator. + type Complex + private Value re:Float im:Float + + new re=0:Float im=0:Float -> Complex = + c = Complex.Value re 0 + if im != 0 then c:Complex else + ${complexNew} + + + self (that:Complex) = Complex.new self.re+that.re self.im+that.im + + < self (that:Complex) = Complex_Comparator.compare self that == Ordering.Less + > self (that:Complex) = Complex_Comparator.compare self that == Ordering.Greater + >= self (that:Complex) = + ordering = Complex_Comparator.compare self that + ordering == Ordering.Greater || ordering == Ordering.Equal + <= self (that:Complex) = + ordering = Complex_Comparator.compare self that + ordering == Ordering.Less || ordering == Ordering.Equal + + Complex.from (that:Number) = Complex.new that + + + Comparable.from (that:Complex) = Comparable.new that Complex_Comparator + Comparable.from (that:Number) = Comparable.new that Complex_Comparator + + type Complex_Comparator + compare x:Complex y:Complex = if x.re==y.re && x.im==y.im then Ordering.Equal else + if x.im==0 && y.im==0 then Ordering.compare x.re y.re else + Nothing + hash x:Complex = if x.im == 0 then Ordering.hash x.re else + 7*x.re + 11*x.im + + ## uses the explicit conversion defined in this private module + Complex.as_complex_and_float self = + self : Complex&Float + + ## explicit "conversion" of `Complex` to `Float` in a private module + used in `as_complex_and_float` + Float.from (that:Complex) = + if that.im == 0 then that.re else + Error.throw <| Illegal_Argument.Error "Cannot convert Complex with imaginary part to Float" + """ .replace("${complexNew}", complexNew); var src = Source.newBuilder("enso", code, "complex.enso").build(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsTest.java index b3364c9b164e..22f435c98c04 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/EqualsTest.java @@ -247,9 +247,11 @@ public void testTruffleString() { public void testTruffleNumberPlus() { var plus100 = ctxRule - .eval("enso", """ - plus100 x = 100+x - """) + .eval( + "enso", + """ + plus100 x = 100+x + """) .invokeMember(MethodNames.Module.EVAL_EXPRESSION, "plus100"); assertTrue("plus100 can be executed", plus100.canExecute()); var foreignNumber = ctxRule.asValue(new WrappedPrimitive(42)); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ExtensionMethodResolutionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ExtensionMethodResolutionTest.java index 359280f4ea33..3282b3d6891a 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ExtensionMethodResolutionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ExtensionMethodResolutionTest.java @@ -41,7 +41,8 @@ public class ExtensionMethodResolutionTest { @Test public void twoExtensionMethodsWithSameNameInOneModuleShouldFail() throws IOException { - var src = """ + var src = + """ type T T.foo x = x T.foo x y = x + y @@ -51,7 +52,8 @@ public void twoExtensionMethodsWithSameNameInOneModuleShouldFail() throws IOExce @Test public void extensionMethodAndNormalMethodConflictInOneModule() throws IOException { - var src = """ + var src = + """ type T foo x = x T.foo x y = x + y @@ -97,7 +99,9 @@ public void firstResolutionIsInTypesScope() throws IOException { @Test public void secondResolutionIsInCurrentModuleScope() throws IOException { var xMod = - new SourceModule(QualifiedName.fromString("X"), """ + new SourceModule( + QualifiedName.fromString("X"), + """ type T """); var yMod = @@ -131,7 +135,9 @@ public void secondResolutionIsInCurrentModuleScope() throws IOException { @Test public void resolutionFromImportedModulesIsDeterministic1() throws IOException { var xMod = - new SourceModule(QualifiedName.fromString("X"), """ + new SourceModule( + QualifiedName.fromString("X"), + """ type T """); var yMod = @@ -173,7 +179,9 @@ public void resolutionFromImportedModulesIsDeterministic1() throws IOException { @Test public void resolutionFromImportedModulesIsDeterministic2() throws IOException { var xMod = - new SourceModule(QualifiedName.fromString("X"), """ + new SourceModule( + QualifiedName.fromString("X"), + """ type T """); var yMod = @@ -276,7 +284,8 @@ public void sameExtensionMethodInDifferentTypes() throws IOException { public void sameExtensionMethodInDifferentTypesInThreeModules() throws IOException { var mod2 = new SourceModule( - QualifiedName.fromString("Mod2"), """ + QualifiedName.fromString("Mod2"), + """ # An empty module """); // The type T defined in mod1 and mainMod have exactly the same location on purpose. diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/FindExceptionMessageTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/FindExceptionMessageTest.java index fecdff03fae9..30ce7d176acc 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/FindExceptionMessageTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/FindExceptionMessageTest.java @@ -22,13 +22,13 @@ public class FindExceptionMessageTest { public void testThrowNPE() { String src = """ - from Standard.Base import Panic - polyglot java import java.lang.NullPointerException + from Standard.Base import Panic + polyglot java import java.lang.NullPointerException - main = - x = NullPointerException.new - Panic.throw x - """; + main = + x = NullPointerException.new + Panic.throw x + """; try { Value res = ctxRule.evalModule(src); @@ -42,13 +42,13 @@ public void testThrowNPE() { public void testThrowNPEWithName() { String src = """ - from Standard.Base import Panic - polyglot java import java.lang.NullPointerException + from Standard.Base import Panic + polyglot java import java.lang.NullPointerException - main = - x = NullPointerException.new "Hello World!" - Panic.throw x - """; + main = + x = NullPointerException.new "Hello World!" + Panic.throw x + """; try { Value res = ctxRule.evalModule(src); @@ -62,15 +62,15 @@ public void testThrowNPEWithName() { public void errorThrowDeep() { var src = """ - from Standard.Base import all - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + from Standard.Base import all + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - deep n = if n <= 0 then Error.throw (Illegal_Argument.Error "Problem"+n.to_text) else deep n-1 + deep n = if n <= 0 then Error.throw (Illegal_Argument.Error "Problem"+n.to_text) else deep n-1 - main = - d = deep 10 - d - """; + main = + d = deep 10 + d + """; var res = ctxRule.evalModule(src); assertTrue("Expecting error: " + res, res.isException()); @@ -90,17 +90,17 @@ public void errorThrowDeep() { public void panicThrowDeepRecoverError() { var src = """ - from Standard.Base import all - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + from Standard.Base import all + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - deep_panic n = if n <= 0 then Panic.throw (Illegal_Argument.Error "Problem") else - deep_panic n-1 + deep_panic n = if n <= 0 then Panic.throw (Illegal_Argument.Error "Problem") else + deep_panic n-1 - main = - d = Panic.recover Any - deep_panic 10 - d - """; + main = + d = Panic.recover Any + deep_panic 10 + d + """; var res = ctxRule.evalModule(src); assertTrue("Expecting recovered error: " + res, res.isException()); @@ -128,23 +128,23 @@ public void panicThrowDeepRecoverError() { public void panicThrowDeepMixingJava() { var src = """ - from Standard.Base import all - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - polyglot java import org.enso.example.TestClass + from Standard.Base import all + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + polyglot java import org.enso.example.TestClass - exec e ~r = - e.execute r... + exec e ~r = + e.execute r... - deep_panic e n = if n <= 0 then Panic.throw (Illegal_Argument.Error "Problem") else - exec e - deep_panic e n-1 + deep_panic e n = if n <= 0 then Panic.throw (Illegal_Argument.Error "Problem") else + exec e + deep_panic e n-1 - main = - e = TestClass.newDirectExecutor - d = Panic.recover Any - deep_panic e 10 - d - """; + main = + e = TestClass.newDirectExecutor + d = Panic.recover Any + deep_panic e 10 + d + """; var res = ctxRule.evalModule(src); assertTrue("Expecting recovered error: " + res, res.isException()); @@ -177,12 +177,12 @@ public void panicThrowDeepMixingJava() { public void testPanic() { String src = """ - from Standard.Base import Panic - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + from Standard.Base import Panic + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - main = Panic.throw (Illegal_Argument.Error 'Jejda!') + main = Panic.throw (Illegal_Argument.Error 'Jejda!') - """; + """; try { Value res = ctxRule.evalModule(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/InterpreterSymbolResolutionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/InterpreterSymbolResolutionTest.java index 273587558256..15745d610172 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/InterpreterSymbolResolutionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/InterpreterSymbolResolutionTest.java @@ -33,9 +33,9 @@ public void resolvingLocalSymbol() throws Exception { Source.newBuilder( "enso", """ - my_symbol = 42 - entry_point = my_symbol - """, + my_symbol = 42 + entry_point = my_symbol + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -53,9 +53,9 @@ public void resolvingSymbolQualifiedThroughCurrentModuleName() throws Exception Source.newBuilder( "enso", """ - my_symbol = 42 - entry_point = currentModuleName.my_symbol - """, + my_symbol = 42 + entry_point = currentModuleName.my_symbol + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -73,10 +73,10 @@ public void resolvingSymbolQualifiedThroughCurrentModuleName2() throws Exception Source.newBuilder( "enso", """ - type My_Type - my_value = 43 - entry_point = Current_Module_Name.My_Type.my_value - """, + type My_Type + my_value = 43 + entry_point = Current_Module_Name.My_Type.my_value + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -98,9 +98,9 @@ public void aliasedModuleName() throws Exception { Source.newBuilder( "enso", """ - aliasedModuleName = 43 - entry_point = aliasedModuleName - """, + aliasedModuleName = 43 + entry_point = aliasedModuleName + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -118,10 +118,10 @@ public void aliasedModuleName2() throws Exception { Source.newBuilder( "enso", """ - type Aliased_Module_Name - my_value = 44 - entry_point = Aliased_Module_Name.my_value - """, + type Aliased_Module_Name + my_value = 44 + entry_point = Aliased_Module_Name.my_value + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/LazyAtomFieldTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/LazyAtomFieldTest.java index 439231d6bda1..d9d7b92f5142 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/LazyAtomFieldTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/LazyAtomFieldTest.java @@ -26,41 +26,41 @@ public void resetOut() { public void evaluation() throws Exception { final String code = """ - from Standard.Base import IO - - type Lazy - LazyValue ~x ~y - - say self w = "Hello " + w.to_text - - meaning self = - IO.println "Computing meaning" - v = self.x * self.y - IO.println "Computed meaning" - v - - meanings = - compute_x = - IO.println "Computing x" - v = 6 - IO.println "Computing x done" - v - - compute_y = - IO.println "Computing y" - v = 7 - IO.println "Computing y done" - v - - IO.println "Start" - l = Lazy.LazyValue compute_x compute_y - IO.println "Lazy value ready" - IO.println <| l.say "World!" - IO.println l.meaning - IO.println <| l.say "Again!" - IO.println l.meaning - l.meaning - """; + from Standard.Base import IO + + type Lazy + LazyValue ~x ~y + + say self w = "Hello " + w.to_text + + meaning self = + IO.println "Computing meaning" + v = self.x * self.y + IO.println "Computed meaning" + v + + meanings = + compute_x = + IO.println "Computing x" + v = 6 + IO.println "Computing x done" + v + + compute_y = + IO.println "Computing y" + v = 7 + IO.println "Computing y done" + v + + IO.println "Start" + l = Lazy.LazyValue compute_x compute_y + IO.println "Lazy value ready" + IO.println <| l.say "World!" + IO.println l.meaning + IO.println <| l.say "Again!" + IO.println l.meaning + l.meaning + """; var meanings = evalCode(code, "meanings"); assertEquals(42, meanings.asInt()); @@ -79,29 +79,29 @@ public void evaluation() throws Exception { public void testInfiniteListGenerator() throws Exception { final String code = """ - import Standard.Base.IO + import Standard.Base.IO - type Lazy - Nil - Cons ~x ~xs + type Lazy + Nil + Cons ~x ~xs - take self n = if n == 0 then Lazy.Nil else case self of - Lazy.Nil -> Lazy.Nil - Lazy.Cons x xs -> Lazy.Cons x (xs.take n-1) + take self n = if n == 0 then Lazy.Nil else case self of + Lazy.Nil -> Lazy.Nil + Lazy.Cons x xs -> Lazy.Cons x (xs.take n-1) - sum self acc = case self of - Lazy.Nil -> acc - Lazy.Cons x xs -> @Tail_Call xs.sum acc+x + sum self acc = case self of + Lazy.Nil -> acc + Lazy.Cons x xs -> @Tail_Call xs.sum acc+x - generator n = Lazy.Cons n (Lazy.generator n+1) + generator n = Lazy.Cons n (Lazy.generator n+1) - both n = - g = Lazy.generator 1 - # IO.println "Generator is computed" - t = g.take n - # IO.println "Generator is taken" - t . sum 0 - """; + both n = + g = Lazy.generator 1 + # IO.println "Generator is computed" + t = g.take n + # IO.println "Generator is taken" + t . sum 0 + """; var both = evalCode(code, "both"); var sum = both.execute(100); @@ -113,44 +113,44 @@ public void testInfiniteListGenerator() throws Exception { public void fourAtomIntFields() throws Exception { checkNumHolder( """ - type Num - Holder a b c ~num + type Num + Holder a b c ~num - new = Num.Holder 1 2 3 (R.new.nextInt) - """); + new = Num.Holder 1 2 3 (R.new.nextInt) + """); } @Test public void fourAtomObjectFields() throws Exception { checkNumHolder( """ - type Num - Holder a b c ~num + type Num + Holder a b c ~num - new = Num.Holder "a" "b" "c" (R.new.nextInt) - """); + new = Num.Holder "a" "b" "c" (R.new.nextInt) + """); } @Test public void fiveAtomIntFields() throws Exception { checkNumHolder( """ - type Num - Holder a b c d ~num + type Num + Holder a b c d ~num - new = Num.Holder 1 2 3 4 (R.new.nextInt) - """); + new = Num.Holder 1 2 3 4 (R.new.nextInt) + """); } @Test public void fiveAtomObjectFields() throws Exception { checkNumHolder( """ - type Num - Holder a b c d ~num + type Num + Holder a b c d ~num - new = Num.Holder "a" "b" "c" "d" (R.new.nextInt) - """); + new = Num.Holder "a" "b" "c" "d" (R.new.nextInt) + """); } @Test @@ -158,19 +158,19 @@ public void toTextOnAtomWithLazyField() throws URISyntaxException { var res = evalCode( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type Generator - Value n ~next + type Generator + Value n ~next - natural = - gen n = Generator.Value n (gen n+1) - gen 2 + natural = + gen n = Generator.Value n (gen n+1) + gen 2 - main _ = - two = natural - two.to_text - """, + main _ = + two = natural + two.to_text + """, "main"); assertTrue(res.isString()); } @@ -181,12 +181,12 @@ private void checkNumHolder(String typeDefinition) throws Exception { + typeDefinition + """ - create ignore = - fbl = Num.new - f = fbl.num - n = fbl.num - [ f, n ] - """; + create ignore = + fbl = Num.new + f = fbl.num + n = fbl.num + [ f, n ] + """; var create = evalCode(code, "create"); var tupple = create.execute(0); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ListTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ListTest.java index 60b0ace3be13..7ad57f35eaf5 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ListTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ListTest.java @@ -33,25 +33,25 @@ public static void prepareCtx() throws Exception { final String code = """ - from Standard.Base.Data.List.List import Cons, Nil + from Standard.Base.Data.List.List import Cons, Nil - init list = list.init + init list = list.init - taken list n = list.take_start n + taken list n = list.take_start n - even_ones list = list.filter (x -> x % 2 == 0) + even_ones list = list.filter (x -> x % 2 == 0) - plus_one list = list.map (x -> x + 1) + plus_one list = list.map (x -> x + 1) - as_vector list = list.to_vector + as_vector list = list.to_vector - as_text list = list.to_text + as_text list = list.to_text - generator n = - go x v l = if x > n then l else - @Tail_Call go x+1 v+1 (Cons v l) - go 1 1 Nil - """; + generator n = + go x v l = if x > n then l else + @Tail_Call go x+1 v+1 (Cons v l) + go 1 1 Nil + """; generator = evalCode(code, "generator"); plusOne = evalCode(code, "plus_one"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/MethodResolutionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/MethodResolutionTest.java index 78fd86668ef4..da381583d42d 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/MethodResolutionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/MethodResolutionTest.java @@ -35,13 +35,13 @@ public void resolveStaticMethodFromAny() { var myTypeVal = ctxRule.evalModule( """ - from Standard.Base import all + from Standard.Base import all - type My_Type - method self = 42 + type My_Type + method self = 42 - main = My_Type - """); + main = My_Type + """); var myType = unwrapType(myTypeVal); var symbol = UnresolvedSymbol.build("to_display_text", myType.getDefinitionScope()); var func = methodResolverNode.executeResolution(myType, symbol); @@ -54,11 +54,11 @@ public void resolveInstanceMethodFromMyType() { var myTypeVal = ctxRule.evalModule( """ - type My_Type - method self = 42 + type My_Type + method self = 42 - main = My_Type - """, + main = My_Type + """, "Module", "main"); var myType = unwrapType(myTypeVal); @@ -73,11 +73,11 @@ public void resolveStaticMethodFromMyType() { var myTypeVal = ctxRule.evalModule( """ - type My_Type - method = 42 + type My_Type + method = 42 - main = My_Type - """, + main = My_Type + """, "Module", "main"); var myType = unwrapType(myTypeVal); @@ -92,11 +92,11 @@ public void resolveExtensionMethodFromMyType() { var myTypeVal = ctxRule.evalModule( """ - type My_Type - My_Type.method = 42 + type My_Type + My_Type.method = 42 - main = My_Type - """, + main = My_Type + """, "Module", "main"); var myType = unwrapType(myTypeVal); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/NativeLibraryFinderTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/NativeLibraryFinderTest.java index 833bf75e08f0..c5ec1de4523a 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/NativeLibraryFinderTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/NativeLibraryFinderTest.java @@ -47,7 +47,8 @@ public void cleanup() { @Test public void standardImageShouldHaveNativeLib() { // Evaluate dummy sources to force loading Standard.Image - ctxRule.evalModule(""" + ctxRule.evalModule( + """ from Standard.Image import all main = 42 """); @@ -67,7 +68,8 @@ public void standardImageShouldHaveNativeLib() { @Test public void standardTableauShouldHaveNativeLib() { // Evaluate dummy sources to force loading Standard.Tableau - ctxRule.evalModule(""" + ctxRule.evalModule( + """ from Standard.Tableau import all main = 42 """); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotErrorTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotErrorTest.java index 37d2bc0c410f..7f969bd0fcf3 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotErrorTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotErrorTest.java @@ -26,72 +26,72 @@ public static void prepareCtx() throws Exception { var code = """ - import Standard.Base.Panic.Panic - import Standard.Base.Data.Text.Text - from Standard.Base.Error import all - import Standard.Base.Errors.Illegal_State.Illegal_State - import Standard.Base.Nothing.Nothing - import Standard.Base.Warning.Warning - polyglot java import org.enso.interpreter.test.PolyglotErrorTest + import Standard.Base.Panic.Panic + import Standard.Base.Data.Text.Text + from Standard.Base.Error import all + import Standard.Base.Errors.Illegal_State.Illegal_State + import Standard.Base.Nothing.Nothing + import Standard.Base.Warning.Warning + polyglot java import org.enso.interpreter.test.PolyglotErrorTest - type TypeCa - Ca x + type TypeCa + Ca x - to_text : Text - to_text self = "<>" + to_text : Text + to_text self = "<>" - type TypeCb - Cb x + type TypeCb + Cb x - to_text : Text - to_text self = Error.throw (Illegal_State.Error "B") + to_text : Text + to_text self = Error.throw (Illegal_State.Error "B") - type TypeCc - Cc x + type TypeCc + Cc x - to_text : Text - to_text self = Panic.throw (Illegal_State.Error "C") + to_text : Text + to_text self = Panic.throw (Illegal_State.Error "C") - type TypeCd - Cd x + type TypeCd + Cd x - to_text self = 42 + to_text self = 42 - type TypeCe - Ce x + type TypeCe + Ce x - to_text self = Warning.attach "Some random warning" self.x + to_text self = Warning.attach "Some random warning" self.x - panic x = case x of - 1 -> panic1 - 2 -> panic2 - 3 -> panic3 - 4 -> panic4 - 5 -> panic5 - 6 -> panic6 - _ -> panic7 + panic x = case x of + 1 -> panic1 + 2 -> panic2 + 3 -> panic3 + 4 -> panic4 + 5 -> panic5 + 6 -> panic6 + _ -> panic7 - panic1 = PolyglotErrorTest.bar (TypeCa.Ca 'x') + panic1 = PolyglotErrorTest.bar (TypeCa.Ca 'x') - panic2 = - PolyglotErrorTest.bar (TypeCb.Cb 'y') . catch err-> - "{Error: "+err.to_text+"}" + panic2 = + PolyglotErrorTest.bar (TypeCb.Cb 'y') . catch err-> + "{Error: "+err.to_text+"}" - panic3 = - Panic.catch Illegal_State (PolyglotErrorTest.bar (TypeCc.Cc 'z')) caught_panic-> - "{Panic: "+caught_panic.payload.to_text+"}" + panic3 = + Panic.catch Illegal_State (PolyglotErrorTest.bar (TypeCc.Cc 'z')) caught_panic-> + "{Panic: "+caught_panic.payload.to_text+"}" - panic4 = PolyglotErrorTest.bar (TypeCd.Cd Nothing) + panic4 = PolyglotErrorTest.bar (TypeCd.Cd Nothing) - panic5 = PolyglotErrorTest.bar (TypeCe.Ce "Foo") - panic6 = PolyglotErrorTest.bar (TypeCe.Ce 44) - panic7 = - j = Error.throw 1 - d = Error.throw 2 - t = j + d - v = [j, d, t] - v - """; + panic5 = PolyglotErrorTest.bar (TypeCe.Ce "Foo") + panic6 = PolyglotErrorTest.bar (TypeCe.Ce 44) + panic7 = + j = Error.throw 1 + d = Error.throw 2 + t = j + d + v = [j, d, t] + v + """; var src = Source.newBuilder("enso", code, "test.enso").build(); var module = ctx.eval(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotFindExceptionMessageTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotFindExceptionMessageTest.java index 9f2f1f07ae73..9c62cb683454 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotFindExceptionMessageTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PolyglotFindExceptionMessageTest.java @@ -17,11 +17,11 @@ public class PolyglotFindExceptionMessageTest { public void testJavaScriptException() { String src = """ - main = err + main = err - foreign js err = \""" - throw Error('Wrong!') - """; + foreign js err = \""" + throw Error('Wrong!') + """; try { Value res = ctxRule.evalModule(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PrintTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PrintTest.java index e769d2a38fb3..4f8578602367 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PrintTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/PrintTest.java @@ -39,23 +39,24 @@ private Value evalCode(final String code, final String methodName) throws URISyn public void testPrintText() throws Exception { final String code = """ - import Standard.Base.IO + import Standard.Base.IO - test = - IO.println "Foobar" - """; + test = + IO.println "Foobar" + """; checkPrint(code, "Foobar"); } @Test public void testPrintPrimitive() throws Exception { - final String code = """ - import Standard.Base.IO + final String code = + """ + import Standard.Base.IO - test = - IO.println 42 - """; + test = + IO.println 42 + """; checkPrint(code, "42"); } @@ -64,16 +65,16 @@ public void testPrintPrimitive() throws Exception { public void testPrintToText() throws Exception { final String code = """ - import Standard.Base.IO + import Standard.Base.IO - type My_Object - Value x + type My_Object + Value x - to_text self = "MyObj{" + self.x.to_text + "}" + to_text self = "MyObj{" + self.x.to_text + "}" - test = - IO.println (My_Object.Value 42) - """; + test = + IO.println (My_Object.Value 42) + """; checkPrint(code, "MyObj{42}"); } @@ -82,16 +83,16 @@ public void testPrintToText() throws Exception { public void testPrintError() throws Exception { final String code = """ - import Standard.Base.IO - import Standard.Base.Error.Error + import Standard.Base.IO + import Standard.Base.Error.Error - type My_Error - Error x + type My_Error + Error x - test = - a = Error.throw (My_Error.Error 1) - IO.println a - """; + test = + a = Error.throw (My_Error.Error 1) + IO.println a + """; checkPrint(code, "(Error: (My_Error.Error 1))"); } @@ -100,13 +101,13 @@ public void testPrintError() throws Exception { public void testPrintToTextHasWarnings() throws Exception { final String code = """ - import Standard.Base.IO - from Standard.Base.Warning import Warning + import Standard.Base.IO + from Standard.Base.Warning import Warning - test = - a = Warning.attach "Warning" "FOOBAR" - IO.println a - """; + test = + a = Warning.attach "Warning" "FOOBAR" + IO.println a + """; checkPrint(code, "FOOBAR"); } @@ -115,13 +116,13 @@ public void testPrintToTextHasWarnings() throws Exception { public void testPrintToTextHasWarnings2() throws Exception { final String code = """ - import Standard.Base.IO - from Standard.Base.Warning import Warning + import Standard.Base.IO + from Standard.Base.Warning import Warning - test = - a = Warning.attach "Warning" 42 - IO.println a - """; + test = + a = Warning.attach "Warning" 42 + IO.println a + """; checkPrint(code, "42"); } @@ -130,18 +131,18 @@ public void testPrintToTextHasWarnings2() throws Exception { public void testPrintToTextHasWarnings3() throws Exception { final String code = """ - import Standard.Base.IO - from Standard.Base.Warning import Warning + import Standard.Base.IO + from Standard.Base.Warning import Warning - type My_Object - Value x + type My_Object + Value x - to_text self = "MyObj{" + self.x.to_text + "}" + to_text self = "MyObj{" + self.x.to_text + "}" - test = - a = Warning.attach "Warning" (My_Object.Value 42) - IO.println a - """; + test = + a = Warning.attach "Warning" (My_Object.Value 42) + IO.println a + """; checkPrint(code, "MyObj{42}"); } @@ -150,20 +151,20 @@ public void testPrintToTextHasWarnings3() throws Exception { public void testPrintToTextHasWarnings4() throws Exception { final String code = """ - import Standard.Base.IO - from Standard.Base.Warning import Warning + import Standard.Base.IO + from Standard.Base.Warning import Warning - type My_Object - Value x + type My_Object + Value x - to_text self = - res = "MyObj{" + self.x.to_text + "}" - Warning.attach "Warning2" res + to_text self = + res = "MyObj{" + self.x.to_text + "}" + Warning.attach "Warning2" res - test = - a = Warning.attach "Warning" (My_Object.Value 42) - IO.println a - """; + test = + a = Warning.attach "Warning" (My_Object.Value 42) + IO.println a + """; checkPrint(code, "MyObj{42}"); } @@ -172,17 +173,17 @@ public void testPrintToTextHasWarnings4() throws Exception { public void testPrintToTextTypeError() throws Exception { final String code = """ - import Standard.Base.IO + import Standard.Base.IO - type My_Object - Value x + type My_Object + Value x - to_text self = 100 + to_text self = 100 - test = - a = My_Object.Value 42 - IO.println a - """; + test = + a = My_Object.Value 42 + IO.println a + """; checkPrint(code, "100"); } @@ -191,20 +192,20 @@ public void testPrintToTextTypeError() throws Exception { public void testPrintToTextTypeErrorAndWarnings() throws Exception { final String code = """ - import Standard.Base.IO - from Standard.Base.Warning import Warning + import Standard.Base.IO + from Standard.Base.Warning import Warning - type My_Object - Value x + type My_Object + Value x - to_text self = - res = 100 - Warning.attach "Warning2" res + to_text self = + res = 100 + Warning.attach "Warning2" res - test = - a = Warning.attach "Warning2" (My_Object.Value 42) - IO.println a - """; + test = + a = Warning.attach "Warning2" (My_Object.Value 42) + IO.println a + """; checkPrint(code, "100"); } @@ -213,17 +214,17 @@ public void testPrintToTextTypeErrorAndWarnings() throws Exception { public void testPrintToTextStaticMethod() throws Exception { final String code = """ - import Standard.Base.IO + import Standard.Base.IO - type My_Object - Value x + type My_Object + Value x - to_text self = "MyObj{" + self.x.to_text + "}" + to_text self = "MyObj{" + self.x.to_text + "}" - test = - a = My_Object - IO.println a - """; + test = + a = My_Object + IO.println a + """; checkPrint(code, "My_Object"); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/RootNamesTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/RootNamesTest.java index 4acce0e60427..7ecdf23b3554 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/RootNamesTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/RootNamesTest.java @@ -44,12 +44,12 @@ public static void initCtx() { Source.newBuilder( "js", """ - insight.on('enter', (ctx, frame) => { - print(`ENTER: ${ctx.name}`); - }, { - roots : true - }); - """, + insight.on('enter', (ctx, frame) => { + print(`ENTER: ${ctx.name}`); + }, { + roots : true + }); + """, "trace.js") .build(); } catch (IOException e) { diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SharedEngineTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SharedEngineTest.java index 261c69b91e48..7b5f24e08e86 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SharedEngineTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SharedEngineTest.java @@ -49,14 +49,14 @@ public static void disposeEngine() { Source.newBuilder( "enso", """ - from Standard.Base import Vector, Text, Number + from Standard.Base import Vector, Text, Number - check x = case x of - _ : Vector -> 1 - _ : Text -> 2 - _ : Number -> 3 - _ -> 4 - """, + check x = case x of + _ : Vector -> 1 + _ : Text -> 2 + _ : Number -> 3 + _ -> 4 + """, "type_case.enso") .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignaturePolyglotTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignaturePolyglotTest.java index 2fabf8d7e3ea..658d59f4cc92 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignaturePolyglotTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignaturePolyglotTest.java @@ -24,12 +24,12 @@ public void polyglotDataTimeFormatter() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all + from Standard.Base import all - polyglot java import java.time.format.DateTimeFormatter + polyglot java import java.time.format.DateTimeFormatter - fn (x : DateTimeFormatter) = x.to_text - """, + fn (x : DateTimeFormatter) = x.to_text + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -63,12 +63,12 @@ public void polyglotDataTimeFormatterAndText() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all + from Standard.Base import all - polyglot java import java.time.format.DateTimeFormatter + polyglot java import java.time.format.DateTimeFormatter - fn x:(DateTimeFormatter | Text) = x.to_text - """, + fn x:(DateTimeFormatter | Text) = x.to_text + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignatureTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignatureTest.java index 12e66e91e301..2bc40bd22606 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignatureTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/SignatureTest.java @@ -29,10 +29,12 @@ public void wrongFunctionSignature() throws Exception { final URI uri = new URI("memory://neg.enso"); final Source src = Source.newBuilder( - "enso", """ - neg : Xyz -> Abc - neg a = 0 - a - """, uri.getAuthority()) + "enso", + """ + neg : Xyz -> Abc + neg a = 0 - a + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -49,9 +51,12 @@ public void wrongFunctionSignature() throws Exception { public void wrongLiteralSignature() throws Exception { final URI uri = new URI("memory://literal_signature.enso"); final Source src = - Source.newBuilder("enso", """ - neg a = 0 - a:Xyz - """, uri.getAuthority()) + Source.newBuilder( + "enso", + """ + neg a = 0 - a:Xyz + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -68,9 +73,12 @@ public void wrongLiteralSignature() throws Exception { public void wrongExpressionSignature() throws Exception { final URI uri = new URI("memory://exp_signature.enso"); final Source src = - Source.newBuilder("enso", """ - neg a = (0 - a):Xyz - """, uri.getAuthority()) + Source.newBuilder( + "enso", + """ + neg a = (0 - a):Xyz + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -87,9 +95,12 @@ public void wrongExpressionSignature() throws Exception { public void wrongAscribedTypeSignature() throws Exception { final URI uri = new URI("memory://neg.enso"); final Source src = - Source.newBuilder("enso", """ - neg (a : Xyz) = 0 - a - """, uri.getAuthority()) + Source.newBuilder( + "enso", + """ + neg (a : Xyz) = 0 - a + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -109,11 +120,11 @@ public void runtimeCheckOfAscribedFunctionSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error + from Standard.Base import Integer, Error - err msg = Error.throw msg - neg (a : Integer) = 0 - a - """, + err msg = Error.throw msg + neg (a : Integer) = 0 - a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -145,21 +156,21 @@ public void lazyIntegerInConstructor() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all + from Standard.Base import all - type Int - Simple v - Complex (~unwrap : Int) + type Int + Simple v + Complex (~unwrap : Int) - value self = case self of - Int.Simple v -> v - Int.Complex unwrap -> unwrap.value + value self = case self of + Int.Simple v -> v + Int.Complex unwrap -> unwrap.value - + self (that:Int) = Int.Simple self.value+that.value + + self (that:Int) = Int.Simple self.value+that.value - simple v = Int.Simple v - complex x y = Int.Complex (x+y) - """, + simple v = Int.Simple v + complex x y = Int.Complex (x+y) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -198,15 +209,15 @@ public void runtimeCheckOfLazyAscribedFunctionSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, IO + from Standard.Base import Integer, IO - build (~zero : Integer) = - neg (~a : Integer) = zero - a - neg + build (~zero : Integer) = + neg (~a : Integer) = zero - a + neg - make arr = build <| - arr.at 0 - """, + make arr = build <| + arr.at 0 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -251,17 +262,17 @@ public void runtimeCheckOfLazyAscribedConstructorSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, IO, Polyglot + from Standard.Base import Integer, IO, Polyglot - type Lazy - Value (~zero : Integer) + type Lazy + Value (~zero : Integer) - neg self (~a : Integer) = self.zero - a + neg self (~a : Integer) = self.zero - a - make arr = Lazy.Value <| - Polyglot.invoke arr "add" [ arr.length ] - arr.at 0 - """, + make arr = Lazy.Value <| + Polyglot.invoke arr "add" [ arr.length ] + arr.at 0 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -302,12 +313,12 @@ public void runtimeCheckOfAscribedInstanceMethodSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - type Neg - Singleton + from Standard.Base import Integer + type Neg + Singleton - twice self (a : Integer) = a + a - """, + twice self (a : Integer) = a + a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -333,10 +344,10 @@ public void runtimeCheckOfAscribedStaticMethodSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - type Neg - twice (a : Integer) = a + a - """, + from Standard.Base import Integer + type Neg + twice (a : Integer) = a + a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -362,12 +373,12 @@ public void runtimeCheckOfAscribedLocalMethodSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - call_twice x = - twice (a : Integer) = a + a - twice x - """, + call_twice x = + twice (a : Integer) = a + a + twice x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -393,18 +404,18 @@ public void runtimeCheckOfSelfType() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all - type My_Type - Value x - f self y = self.x+y - - type Other_Type - Ctor x - - normal_call = (My_Type.Value 42).f 10 - static_call = My_Type.f (My_Type.Value 23) 100 - invalid_static_call = My_Type.f (Other_Type.Ctor 11) 1000 - """, + from Standard.Base import all + type My_Type + Value x + f self y = self.x+y + + type Other_Type + Ctor x + + normal_call = (My_Type.Value 42).f 10 + static_call = My_Type.f (My_Type.Value 23) 100 + invalid_static_call = My_Type.f (Other_Type.Ctor 11) 1000 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -432,11 +443,11 @@ public void wrongAscribedInConstructor() throws Exception { Source.newBuilder( "enso", """ - type Neg - Val (a : Xyz) + type Neg + Val (a : Xyz) - neg = Neg.Val 10 - """, + neg = Neg.Val 10 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -457,10 +468,10 @@ public void ascribedWithAParameter() throws Exception { Source.newBuilder( "enso", """ - type Maybe a - Nothing - Some unwrap:a - """, + type Maybe a + Nothing + Some unwrap:a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -477,13 +488,13 @@ public void ascribedWithAParameterAndMethod() throws Exception { Source.newBuilder( "enso", """ - type Maybe a - Nothing - Some unwrap:a + type Maybe a + Nothing + Some unwrap:a - get : a - get self = self.unwrap - """, + get : a + get self = self.unwrap + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -500,12 +511,12 @@ public void suspendedAscribedParameter() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - type Maybe a - Nothing - Some (~unwrap : Integer) - """, + type Maybe a + Nothing + Some (~unwrap : Integer) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -547,10 +558,10 @@ public void panicSentinelSupersedesTypeError() throws URISyntaxException { Source.newBuilder( "enso", """ - from Standard.Base import Integer - my_func (x : Integer) = x + 1 - main = my_func (Non_Existing_Func 23) - """, + from Standard.Base import Integer + my_func (x : Integer) = x + 1 + main = my_func (Non_Existing_Func 23) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -570,21 +581,21 @@ public void automaticConversionToAType() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - type V - Val (a : Integer) + type V + Val (a : Integer) - # mul accepts V as the other parameter - mul self (other : V) = V.Val self.a*other.a + # mul accepts V as the other parameter + mul self (other : V) = V.Val self.a*other.a - V.from (that : Integer) = V.Val that + V.from (that : Integer) = V.Val that - create x:Integer = V.from x + create x:Integer = V.from x - # invokes V.mul with Integer parameter, not V! - mix a:V b:Integer = a.mul b - """, + # invokes V.mul with Integer parameter, not V! + mix a:V b:Integer = a.mul b + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -607,23 +618,23 @@ public void selfTypeConversion() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all - type My_Type - Value x - f self y = self.x+y + from Standard.Base import all + type My_Type + Value x + f self y = self.x+y - type Convertible_Type - A x + type Convertible_Type + A x - type Inconvertible_Type - B x + type Inconvertible_Type + B x - My_Type.from (that : Convertible_Type) = My_Type.Value that.x+1 + My_Type.from (that : Convertible_Type) = My_Type.Value that.x+1 - static_my_type = My_Type.f (My_Type.Value 23) 1000 - static_convertible = My_Type.f (Convertible_Type.A 23) 1000 - static_inconvertible = My_Type.f (Inconvertible_Type.B 23) 1000 - """, + static_my_type = My_Type.f (My_Type.Value 23) 1000 + static_convertible = My_Type.f (Convertible_Type.A 23) 1000 + static_inconvertible = My_Type.f (Inconvertible_Type.B 23) 1000 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -655,17 +666,17 @@ private Value exampleWithBinary() throws URISyntaxException { Source.newBuilder( "enso", """ - from Standard.Base import all + from Standard.Base import all - type Zero - type One + type Zero + type One - type Bin - Zero (v:Zero) - One (v:One) - Either v:(Zero | One) - Vec v:(Integer | Range | Vector (Integer | Range)) - """, + type Bin + Zero (v:Zero) + One (v:One) + Either v:(Zero | One) + Vec v:(Integer | Range | Vector (Integer | Range)) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -730,17 +741,17 @@ public void partiallyAppliedConstructor() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - type V - Val a b c + type V + Val a b c - create x:V = x.a + x.b + x.c + create x:V = x.a + x.b + x.c - mix a = - partial = V.Val 1 a - create partial - """, + mix a = + partial = V.Val 1 a + create partial + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -768,17 +779,17 @@ public void oversaturatedFunction() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - fn a b c = - sum = a + b + c - add a = sum + a - add + fn a b c = + sum = a + b + c + add a = sum + a + add - neg x:Integer = -x + neg x:Integer = -x - mix n = neg (fn 2 a=4 n) - """, + mix n = neg (fn 2 a=4 n) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -807,16 +818,16 @@ public void suspendedArgumentsUnappliedFunction() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer + from Standard.Base import Integer - fn ~a ~b ~c = - add x = if x == 0 then 0 else x * (a + b + c) - add + fn ~a ~b ~c = + add x = if x == 0 then 0 else x * (a + b + c) + add - neg x:Integer = -x + neg x:Integer = -x - mix a = neg (fn c=(2/0) b=(a/0)) - """, + mix a = neg (fn c=(2/0) b=(a/0)) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -845,33 +856,33 @@ public void andConversions() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all + from Standard.Base import all - type Plus - Impl value dict + type Plus + Impl value dict - + self (that:Plus) = if self.dict != that.dict then Panic.throw "panic!" else - self.dict.plus self.value that.value - type Mul - Impl value dict + + self (that:Plus) = if self.dict != that.dict then Panic.throw "panic!" else + self.dict.plus self.value that.value + type Mul + Impl value dict - * self (that:Mul) = if self.dict != that.dict then Panic.throw "panic!" else - self.dict.mul self.value that.value + * self (that:Mul) = if self.dict != that.dict then Panic.throw "panic!" else + self.dict.mul self.value that.value - compute (a : Plus & Mul) (b : Plus & Mul) = - p = a+b - m = a*b - p:Plus + m:Plus + compute (a : Plus & Mul) (b : Plus & Mul) = + p = a+b + m = a*b + p:Plus + m:Plus - type BooleanPlus - plus a:Boolean b:Boolean = a || b - Plus.from(that:Boolean) = Plus.Impl that BooleanPlus + type BooleanPlus + plus a:Boolean b:Boolean = a || b + Plus.from(that:Boolean) = Plus.Impl that BooleanPlus - type BooleanMul - mul a:Boolean b:Boolean = a && b - Mul.from(that:Boolean) = Mul.Impl that BooleanMul + type BooleanMul + mul a:Boolean b:Boolean = a && b + Mul.from(that:Boolean) = Mul.Impl that BooleanMul - """, + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -891,9 +902,9 @@ public void unionInArgument() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all - foo (arg : Integer | Text) = arg - """, + from Standard.Base import all + foo (arg : Integer | Text) = arg + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -915,9 +926,12 @@ public void unionInArgument() throws Exception { public void unresolvedReturnTypeSignature() throws Exception { final URI uri = new URI("memory://neg.enso"); final Source src = - Source.newBuilder("enso", """ - neg a -> Xyz = 0 - a - """, uri.getAuthority()) + Source.newBuilder( + "enso", + """ + neg a -> Xyz = 0 - a + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -938,10 +952,10 @@ public void validReturnTypeSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - add1 a b -> Integer = a+b - add2 (a : Integer) (b : Integer) -> Integer = a+b - """, + from Standard.Base import Integer + add1 a b -> Integer = a+b + add2 (a : Integer) (b : Integer) -> Integer = a+b + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -961,9 +975,9 @@ public void returnTypeCheckOptInError() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - plusChecked a b -> Integer = b+a - """, + from Standard.Base import Integer + plusChecked a b -> Integer = b+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1080,10 +1094,10 @@ public void returnTypeCheckOptOut() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - plusUnchecked : Integer -> Integer -> Integer - plusUnchecked a b = b+a - """, + from Standard.Base import Integer + plusUnchecked : Integer -> Integer -> Integer + plusUnchecked a b = b+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1102,10 +1116,10 @@ public void returnTypeCheckOptInErrorZeroArguments() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - constant -> Integer = "foo" - foo a b = a + constant + b - """, + from Standard.Base import Integer + constant -> Integer = "foo" + foo a b = a + constant + b + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1128,11 +1142,11 @@ public void returnTypeCheckOptInErrorZeroArgumentsExpression() throws Exception Source.newBuilder( "enso", """ - from Standard.Base import Integer - foo a = - x -> Integer = a+a - x+x - """, + from Standard.Base import Integer + foo a = + x -> Integer = a+a + x+x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1155,12 +1169,12 @@ public void returnTypeCheckOptInErrorZeroArgumentsBlock() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, IO - foo a = - x -> Integer = - a+a - x+x - """, + from Standard.Base import Integer, IO + foo a = + x -> Integer = + a+a + x+x + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1183,13 +1197,13 @@ public void returnTypeCheckOptInAllowDataflowErrors() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error - foo x -> Integer = case x of - 1 -> 100 - 2 -> "TWO" - 3 -> Error.throw "My error" - _ -> x+1 - """, + from Standard.Base import Integer, Error + foo x -> Integer = case x of + 1 -> 100 + 2 -> "TWO" + 3 -> Error.throw "My error" + _ -> x+1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1217,14 +1231,14 @@ public void returnTypeCheckOptInTailRec() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error - factorial (x : Integer) -> Integer = - go n acc -> Integer = - if n == 0 then acc else - if n == 10 then "TEN :)" else - @Tail_Call go (n-1) (acc*n) - go x 1 - """, + from Standard.Base import Integer, Error + factorial (x : Integer) -> Integer = + go n acc -> Integer = + if n == 0 then acc else + if n == 10 then "TEN :)" else + @Tail_Call go (n-1) (acc*n) + go x 1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1253,14 +1267,14 @@ public void returnTypeCheckOptInTCO() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error - foo (counter : Integer) (trap : Integer) -> Integer = - go i acc -> Integer = - if i == 0 then acc else - if i == trap then "TRAP!" else - @Tail_Call go (i-1) (acc+1) - go counter 1 - """, + from Standard.Base import Integer, Error + foo (counter : Integer) (trap : Integer) -> Integer = + go i acc -> Integer = + if i == 0 then acc else + if i == trap then "TRAP!" else + @Tail_Call go (i-1) (acc+1) + go counter 1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1284,14 +1298,14 @@ public void returnTypeCheckOptInTCO2() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error - foo_ok counter -> Integer = - if counter == 0 then 0 else - @Tail_Call foo_ok (counter-1) - foo_bad counter -> Integer = - if counter == 0 then "ZERO" else - @Tail_Call foo_bad (counter-1) - """, + from Standard.Base import Integer, Error + foo_ok counter -> Integer = + if counter == 0 then 0 else + @Tail_Call foo_ok (counter-1) + foo_bad counter -> Integer = + if counter == 0 then "ZERO" else + @Tail_Call foo_bad (counter-1) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1319,11 +1333,11 @@ public void returnTypeCheckErrorSignature() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - import Standard.Base.Errors.Illegal_State.Illegal_State - foo a -> Integer ! Illegal_State = - a+a - """, + from Standard.Base import Integer + import Standard.Base.Errors.Illegal_State.Illegal_State + foo a -> Integer ! Illegal_State = + a+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1352,13 +1366,13 @@ public void returnTypeCheckErrorSignatureAllowsAllErrors() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Error - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - import Standard.Base.Errors.Illegal_State.Illegal_State + from Standard.Base import Integer, Error + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + import Standard.Base.Errors.Illegal_State.Illegal_State - foo a -> Integer ! Illegal_State = - Error.throw (Illegal_Argument.Error "foo: "+a.to_text) - """, + foo a -> Integer ! Illegal_State = + Error.throw (Illegal_Argument.Error "foo: "+a.to_text) + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1377,10 +1391,10 @@ public void returnTypeCheckSum() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Text - foo a -> Integer | Text = - a+a - """, + from Standard.Base import Integer, Text + foo a -> Integer | Text = + a+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1407,14 +1421,14 @@ public void returnTypeCheckProduct() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer, Text - type Clazz - Value a - Clazz.from (that : Integer) = Clazz.Value that - - foo a -> (Integer | Text) & Clazz = - a+a - """, + from Standard.Base import Integer, Text + type Clazz + Value a + Clazz.from (that : Integer) = Clazz.Value that + + foo a -> (Integer | Text) & Clazz = + a+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -1440,12 +1454,12 @@ public void returnTypeCheckOptInErrorMethodsOnTypes() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Integer - type My_Type - Value - plus_member self a b -> Integer = b+a - plus_static a b -> Integer = b+a - """, + from Standard.Base import Integer + type My_Type + Value + plus_member self a b -> Integer = b+a + plus_static a b -> Integer = b+a + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLoggingTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLoggingTest.java index 70fb87e4b57a..e7ca0f173caf 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLoggingTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLoggingTest.java @@ -19,11 +19,11 @@ public class StdLibLoggingTest { Source.newBuilder( "enso", """ - polyglot java import org.enso.example.LoggingTestUtils + polyglot java import org.enso.example.LoggingTestUtils - test = - LoggingTestUtils.logSomething - """, + test = + LoggingTestUtils.logSomething + """, "logs.enso") .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLogsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLogsTest.java index 5170ab515798..22a5bfaadeff 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLogsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/StdLibLogsTest.java @@ -27,16 +27,16 @@ public static void initEnsoContext() { ctxRule.eval( "enso", """ - from Standard.Base import IO - from Standard.Base.Logging import all + from Standard.Base import IO + from Standard.Base.Logging import all - type Foo + type Foo - test = - Foo.log_message level=..Warning "I should warn you about something..." - Foo.log_message level=..Info "Should be seen? By default we only show up-to warnings level" - Foo.log_message level=..Severe "Something went really bad!" - """); + test = + Foo.log_message level=..Warning "I should warn you about something..." + Foo.log_message level=..Info "Should be seen? By default we only show up-to warnings level" + Foo.log_message level=..Severe "Something went really bad!" + """); } @AfterClass diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/TypeInferenceConsistencyTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/TypeInferenceConsistencyTest.java index 301f088ff034..2123155df0eb 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/TypeInferenceConsistencyTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/TypeInferenceConsistencyTest.java @@ -41,9 +41,12 @@ private String getOutput() { public void notInvokableTest() throws Exception { final URI uri = new URI("memory://notInvokableTest.enso"); final Source src = - Source.newBuilder("enso", """ - foo = 1 2 - """, uri.getAuthority()) + Source.newBuilder( + "enso", + """ + foo = 1 2 + """, + uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -70,13 +73,13 @@ public void notInvokableFunctionNoWarning() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Numbers - import Standard.Base.Function.Function - foo (fun : Function) = - f = fun - x1 = f 123 - x1 - """, + import Standard.Base.Data.Numbers + import Standard.Base.Function.Function + foo (fun : Function) = + f = fun + x1 = f 123 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -96,14 +99,14 @@ public void notInvokableSumTypeNoWarning() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Numbers - import Standard.Base.Data.Numbers.Integer - import Standard.Base.Function.Function - foo (fun : Function | Integer) = - f = fun - x1 = f 123 - x1 - """, + import Standard.Base.Data.Numbers + import Standard.Base.Data.Numbers.Integer + import Standard.Base.Function.Function + foo (fun : Function | Integer) = + f = fun + x1 = f 123 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -130,13 +133,13 @@ public void notInvokableAnyNoWarning() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Any.Any - import Standard.Base.Data.Numbers - foo (fun : Any) = - f = fun - x1 = f 123 - x1 - """, + import Standard.Base.Any.Any + import Standard.Base.Data.Numbers + foo (fun : Any) = + f = fun + x1 = f 123 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -162,13 +165,13 @@ public void notInvokableWrongSumType() throws Exception { Source.newBuilder( "enso", """ - foo x = - f = case x of - 1 -> 33 - _ -> "foo" - x1 = f 123 - x1 - """, + foo x = + f = case x of + 1 -> 33 + _ -> "foo" + x1 = f 123 + x1 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -202,16 +205,16 @@ public void noTypeErrorIfConversionExistsFunctions() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Function.Function - type My_Type - Value v - - My_Type.from (that : Function) = My_Type.Value (that 1) - foo = - f x = x+100 - y = (f : My_Type) - y - """, + import Standard.Base.Function.Function + type My_Type + Value v + + My_Type.from (that : Function) = My_Type.Value (that 1) + foo = + f x = x+100 + y = (f : My_Type) + y + """, uri.getAuthority()) .uri(uri) .buildLiteral(); @@ -249,9 +252,9 @@ public void microDistributionBase() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import all - foo = (123 + 10000).to_text.take 3 - """, + from Standard.Base import all + foo = (123 + 10000).to_text.take 3 + """, uri.getAuthority()) .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ValuesGenerator.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ValuesGenerator.java index 6dfa867ea971..9cd9357a9e5c 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ValuesGenerator.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/ValuesGenerator.java @@ -91,13 +91,13 @@ private ValueInfo v(String key, String prelude, String typeOrValue, String typeC ctx.eval( "enso", """ - {import} + {import} - check x = case x of - _ : {type} -> 1 - _ -> 0 + check x = case x of + _ : {type} -> 1 + _ -> 0 - """ + """ .replace("{type}", typeCheck) .replace("{import}", prelude)); var check = c.invokeMember(MethodNames.Module.EVAL_EXPRESSION, "check"); @@ -143,11 +143,11 @@ private List createValuesOfCustomType( } sb.append( """ - check_{i} x = case x of - _ : {type} -> 1 - _ -> 0 + check_{i} x = case x of + _ : {type} -> 1 + _ -> 0 - """ + """ .replace("{type}", c) .replace("{i}", "" + i)); } @@ -168,23 +168,31 @@ private List createValuesOfCustomType( } public Value typeAny() { - return v("typeAny", """ - import Standard.Base.Any.Any - """, "Any").type(); + return v( + "typeAny", + """ + import Standard.Base.Any.Any + """, + "Any") + .type(); } public Value typeNothing() { - return v("typeNothing", """ - import Standard.Base.Nothing.Nothing - """, "Nothing").type(); + return v( + "typeNothing", + """ + import Standard.Base.Nothing.Nothing + """, + "Nothing") + .type(); } public Value typeNumber() { return v( "typeNumber", """ - from Standard.Base import Nothing, Vector, Number, Float, Integer - """, + from Standard.Base import Nothing, Vector, Number, Float, Integer + """, "Number") .type(); } @@ -193,8 +201,8 @@ public Value typeInteger() { return v( "typeInteger", """ - from Standard.Base import Nothing, Vector, Number, Float, Integer - """, + from Standard.Base import Nothing, Vector, Number, Float, Integer + """, "Integer") .type(); } @@ -203,16 +211,19 @@ public Value typeFloat() { return v( "typeFloat", """ - from Standard.Base import Nothing, Vector, Number, Float, Integer - """, + from Standard.Base import Nothing, Vector, Number, Float, Integer + """, "Float") .type(); } public Value typeBoolean() { - return v("typeBoolean", """ - import Standard.Base.Data.Boolean.Boolean - """, "Boolean") + return v( + "typeBoolean", + """ + import Standard.Base.Data.Boolean.Boolean + """, + "Boolean") .type(); } @@ -220,30 +231,38 @@ public Value typeArrayProxy() { return v( "typeArrayProxy", """ - import Standard.Base.Data.Array_Proxy.Array_Proxy - """, + import Standard.Base.Data.Array_Proxy.Array_Proxy + """, "Array_Proxy") .type(); } public Value typeText() { - return v("typeText", """ - import Standard.Base.Data.Text.Text - """, "Text").type(); + return v( + "typeText", + """ + import Standard.Base.Data.Text.Text + """, + "Text") + .type(); } public Value typeDate() { - return v("typeDate", """ - import Standard.Base.Data.Time.Date.Date - """, "Date").type(); + return v( + "typeDate", + """ + import Standard.Base.Data.Time.Date.Date + """, + "Date") + .type(); } public Value typeDatePeriod() { return v( "typeDate_Period", """ - import Standard.Base.Data.Time.Date_Period.Date_Period - """, + import Standard.Base.Data.Time.Date_Period.Date_Period + """, "Date_Period") .type(); } @@ -252,8 +271,8 @@ public Value typeDateTime() { return v( "typeDate_Time", """ - import Standard.Base.Data.Time.Date_Time.Date_Time - """, + import Standard.Base.Data.Time.Date_Time.Date_Time + """, "Date_Time") .type(); } @@ -262,8 +281,8 @@ public Value typeTimeOfDay() { return v( "typeTimeOfDay", """ - import Standard.Base.Data.Time.Time_Of_Day.Time_Of_Day - """, + import Standard.Base.Data.Time.Time_Of_Day.Time_Of_Day + """, "Time_Of_Day") .type(); } @@ -272,16 +291,19 @@ public Value typeDuration() { return v( "typeDuration", """ - import Standard.Base.Data.Time.Duration.Duration - """, + import Standard.Base.Data.Time.Duration.Duration + """, "Duration") .type(); } public Value typePeriod() { - return v("typePeriod", """ - import Standard.Base.Data.Time.Period.Period - """, "Period") + return v( + "typePeriod", + """ + import Standard.Base.Data.Time.Period.Period + """, + "Period") .type(); } @@ -289,8 +311,8 @@ public Value typeTimePeriod() { return v( "typeTimePeriod", """ - import Standard.Base.Data.Time.Time_Period.Time_Period - """, + import Standard.Base.Data.Time.Time_Period.Time_Period + """, "Time_Period") .type(); } @@ -299,29 +321,39 @@ public Value typeTimeZone() { return v( "typeTimeZone", """ - import Standard.Base.Data.Time.Time_Zone.Time_Zone - """, + import Standard.Base.Data.Time.Time_Zone.Time_Zone + """, "Time_Zone") .type(); } public Value typeArray() { - return v("typeArray", """ - import Standard.Base.Data.Array.Array - """, "Array").type(); + return v( + "typeArray", + """ + import Standard.Base.Data.Array.Array + """, + "Array") + .type(); } public Value typeVector() { - return v("typeVector", """ - import Standard.Base.Data.Vector.Vector - """, "Vector") + return v( + "typeVector", + """ + import Standard.Base.Data.Vector.Vector + """, + "Vector") .type(); } public Value typeNoWrap() { - return v("typeNoWrap", """ - import Standard.Base.Data.Vector.No_Wrap - """, "No_Wrap") + return v( + "typeNoWrap", + """ + import Standard.Base.Data.Vector.No_Wrap + """, + "No_Wrap") .type(); } @@ -329,8 +361,8 @@ public Value typeProblemBehavior() { return v( "typeProblemBehavior", """ - import Standard.Base.Errors.Problem_Behavior.Problem_Behavior - """, + import Standard.Base.Errors.Problem_Behavior.Problem_Behavior + """, "Problem_Behavior") .type(); } @@ -339,55 +371,78 @@ public Value typeMap() { return v( "typeMap", """ - import Standard.Base.Data.Dictionary.Dictionary - """, + import Standard.Base.Data.Dictionary.Dictionary + """, "Dictionary") .type(); } public Value typeWarning() { - return v("typeWarning", """ - import Standard.Base.Warning.Warning - """, "Warning").type(); + return v( + "typeWarning", + """ + import Standard.Base.Warning.Warning + """, + "Warning") + .type(); } public Value typeFile() { - return v("typeFile", """ - import Standard.Base.System.File.File - """, "File").type(); + return v( + "typeFile", + """ + import Standard.Base.System.File.File + """, + "File") + .type(); } public Value typeRef() { - return v("typeRef", """ - import Standard.Base.Runtime.Ref.Ref - """, "Ref").type(); + return v( + "typeRef", + """ + import Standard.Base.Runtime.Ref.Ref + """, + "Ref") + .type(); } public Value typeFunction() { - return v("typeFunction", """ - import Standard.Base.Function.Function - """, "Function") + return v( + "typeFunction", + """ + import Standard.Base.Function.Function + """, + "Function") .type(); } public Value typeError() { - return v("typeError", """ - import Standard.Base.Error.Error - """, "Error").type(); + return v( + "typeError", + """ + import Standard.Base.Error.Error + """, + "Error") + .type(); } public Value typePanic() { - return v("typePanic", """ - import Standard.Base.Panic.Panic - """, "Panic").type(); + return v( + "typePanic", + """ + import Standard.Base.Panic.Panic + """, + "Panic") + .type(); } public Value typeManagedResource() { return v( "typeManaged_Resource", """ - import Standard.Base.Runtime.Managed_Resource.Managed_Resource - """, + import Standard.Base.Runtime.Managed_Resource.Managed_Resource + """, "Managed_Resource") .type(); } @@ -417,11 +472,11 @@ public List numbers() { v( null, """ - from Standard.Base.Data.Ordering import all + from Standard.Base.Data.Ordering import all - fac s n = if n <= 1 then s else - @Tail_Call fac n*s n-1 - """, + fac s n = if n <= 1 then s else + @Tail_Call fac n*s n-1 + """, "fac 1 100") .type()); collect.add(v(null, "", "123 * 10^40").type()); @@ -466,11 +521,11 @@ public List textual() { null, "", """ - ''' - block of - multi-line - texts - """) + ''' + block of + multi-line + texts + """) .type()); } @@ -612,10 +667,10 @@ public List durations() { v( null, """ - import Standard.Base.Data.Time.Duration.Duration - import Standard.Base.Data.Time.Date_Time.Date_Time - from Standard.Base.Data.Boolean.Boolean import False - """, + import Standard.Base.Data.Time.Duration.Duration + import Standard.Base.Data.Time.Date_Time.Date_Time + from Standard.Base.Data.Boolean.Boolean import False + """, expr) .type()); } @@ -677,8 +732,8 @@ public List arrayLike() { v( null, """ - import Standard.Base.Data.Array_Proxy.Array_Proxy - """, + import Standard.Base.Data.Array_Proxy.Array_Proxy + """, "Array_Proxy.new 10 (x -> 2 * x)") .type()); } @@ -754,13 +809,13 @@ public List maps() { ctx.eval( "js", """ - (function() { - var map = new Map(); - map.set('A', 1); - map.set('B', 2); - return map; - }) - """); + (function() { + var map = new Map(); + map.set('A', 1); + map.set('B', 2); + return map; + }) + """); collect.add(fn.execute()); } return collect; @@ -825,9 +880,9 @@ public List constructorsAndValuesAndSumType() { if (languages.contains(Language.ENSO)) { var code = """ - type Sum_Type - Variant_A x - Variant_B y + type Sum_Type + Variant_A x + Variant_B y """; var constructors = List.of( @@ -920,9 +975,9 @@ public List errors() { v( null, """ - import Standard.Base.Any.Any - import Standard.Base.Error.Error - """, + import Standard.Base.Any.Any + import Standard.Base.Error.Error + """, "Error.throw 'In error'") .type()); @@ -931,9 +986,9 @@ public List errors() { v( null, """ - import Standard.Base.Any.Any - import Standard.Base.Panic.Panic - """, + import Standard.Base.Any.Any + import Standard.Base.Panic.Panic + """, "Panic.throw 'In panic'") .type(); assertNull("Exception thrown instead", noValue); @@ -958,8 +1013,8 @@ public List warnings() { v( null, """ - import Standard.Base.Warning.Warning - """, + import Standard.Base.Warning.Warning + """, "Warning.attach 'err' 'value'") .type()); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorBuilderTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorBuilderTest.java index 62ccbe6a3715..685b2bc98cef 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorBuilderTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorBuilderTest.java @@ -30,16 +30,16 @@ public static void initCreate() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Vector.Builder - from Standard.Base.Data.Vector import Vector + import Standard.Base.Data.Vector.Builder + from Standard.Base.Data.Vector import Vector - create pw x y z = - b = Builder.new propagate_warnings=pw - b.append x - b.append y - b.append z - b.to_vector - """, + create pw x y z = + b = Builder.new propagate_warnings=pw + b.append x + b.append y + b.append z + b.to_vector + """, "choose.enso") .uri(srcUri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorSortTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorSortTest.java index ebe4b4daaf2f..f091d8f4cc7e 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorSortTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorSortTest.java @@ -30,11 +30,11 @@ public class VectorSortTest { public static void initNodes() { var code = """ - from Standard.Base import all + from Standard.Base import all - sort val1 val2 = [val1, val2].sort - equals val1 val2 = val1 == val2 - """; + sort val1 val2 = [val1, val2].sort + equals val1 val2 = val1 == val2 + """; sortFunc = ctxRule.getMethodFromModule(code, "sort"); equalsFunc = ctxRule.getMethodFromModule(code, "equals"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorTest.java index 0ae31c4ebc35..7d339121cff3 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/VectorTest.java @@ -28,15 +28,15 @@ public void evaluation() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Vector + import Standard.Base.Data.Vector - choose x = case x of - Vector -> "is vector module" - _ : Vector.Vector -> "is vector type" - _ -> "nothing" + choose x = case x of + Vector -> "is vector module" + _ : Vector.Vector -> "is vector type" + _ -> "nothing" - check = choose [1, 2, 3] - """, + check = choose [1, 2, 3] + """, "choose.enso") .uri(facUri) .buildLiteral(); @@ -50,9 +50,12 @@ public void evaluation() throws Exception { public void vectorToString() throws Exception { final URI facUri = new URI("memory://vector.enso"); final Source src = - Source.newBuilder("enso", """ - check = [1, 2, 3] - """, "vector.enso") + Source.newBuilder( + "enso", + """ + check = [1, 2, 3] + """, + "vector.enso") .uri(facUri) .buildLiteral(); @@ -65,9 +68,12 @@ public void vectorToString() throws Exception { public void arrayToString() throws Exception { final URI facUri = new URI("memory://vector.enso"); final Source src = - Source.newBuilder("enso", """ - check = [1, 2, 3].to_array - """, "vector.enso") + Source.newBuilder( + "enso", + """ + check = [1, 2, 3].to_array + """, + "vector.enso") .uri(facUri) .buildLiteral(); @@ -83,10 +89,10 @@ public void passingVectorDirectlyIntoJava() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Vector + import Standard.Base.Data.Vector - callback f = f.accept ([1, 2, 3].map +5) - """, + callback f = f.accept ([1, 2, 3].map +5) + """, "callback.enso") .uri(uri) .buildLiteral(); @@ -122,12 +128,12 @@ public void passingListOrArrayToEnsoAsArray() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Array.Array + import Standard.Base.Data.Array.Array - how_long array = case array of - arr : Array -> arr.length - _ -> -1 - """, + how_long array = case array of + arr : Array -> arr.length + _ -> -1 + """, "how_long.enso") .uri(uri) .buildLiteral(); @@ -190,21 +196,21 @@ private void warningsInContainer(int type, int callType) throws Exception { Source.newBuilder( "enso", """ - from Standard.Base import Warning - - cb f type call_type = - v = [Warning.attach "OKeyish" 20] - container = case type of - 1 -> v - 2 -> v.to_array - 3 -> v.to_array.to_vector - 4 -> (v+[42]).slice 0 1 - 5 -> ([42]+v).slice 1 2 - - case call_type of - 1 -> container.each f - 2 -> container.map f - """, + from Standard.Base import Warning + + cb f type call_type = + v = [Warning.attach "OKeyish" 20] + container = case type of + 1 -> v + 2 -> v.to_array + 3 -> v.to_array.to_vector + 4 -> (v+[42]).slice 0 1 + 5 -> ([42]+v).slice 1 2 + + case call_type of + 1 -> container.each f + 2 -> container.map f + """, "warning.enso") .uri(srcUri) .buildLiteral(); @@ -280,14 +286,14 @@ private void noCopyTest(String factoryName) throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.Data.Vector.Vector - polyglot java import org.enso.interpreter.test.VectorTest + import Standard.Base.Data.Vector.Vector + polyglot java import org.enso.interpreter.test.VectorTest - raw = VectorTest.${call} - copy = Vector.from_array VectorTest.${call} - lazy = Vector.from_polyglot_array VectorTest.${call} + raw = VectorTest.${call} + copy = Vector.from_array VectorTest.${call} + lazy = Vector.from_polyglot_array VectorTest.${call} - """ + """ .replace("${call}", factoryName), "vectors.enso") .uri(uri) diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/WarningsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/WarningsTest.java index 253800de8007..2389f88212bd 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/WarningsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/WarningsTest.java @@ -51,10 +51,10 @@ public static void initEnsoContext() { ctxRule.eval( "enso", """ - from Standard.Base import Warning + from Standard.Base import Warning - wrap msg value = Warning.attach msg value - """); + wrap msg value = Warning.attach msg value + """); wrap = module.invokeMember(MethodNames.Module.EVAL_EXPRESSION, "wrap"); } @@ -155,17 +155,17 @@ public void allWarningsAreExceptions() throws Exception { public void toDisplayText() throws Exception { var code = """ - from Standard.Base import Integer, Warning, Error, Text + from Standard.Base import Integer, Warning, Error, Text - type My_Warning - private Value msg + type My_Warning + private Value msg - to_display_text self -> Text = Error.throw "Don't call me!" - to_text self -> Text = "My_Warning to_text: "+self.msg + to_display_text self -> Text = Error.throw "Don't call me!" + to_text self -> Text = "My_Warning to_text: "+self.msg - fn = - Warning.attach (My_Warning.Value "ONE") 1 - """; + fn = + Warning.attach (My_Warning.Value "ONE") 1 + """; var module = ctxRule.eval(LanguageInfo.ID, code); var ownWarning = module.invokeMember(MethodNames.Module.EVAL_EXPRESSION, "fn"); @@ -217,15 +217,15 @@ private void assertWarningsForAType(Value v) { public void warningOnAnError() throws Exception { var code = """ - from Standard.Base import Integer, Warning, Error - import Standard.Base.Errors.Illegal_Argument.Illegal_Argument - from Standard.Base.Errors.Common import Out_Of_Range - - err_warn -> Integer ! Illegal_Argument = - v = Warning.attach (Out_Of_Range.Error "qewr") 12 - case v of - _ : Integer -> Error.throw (Illegal_Argument.Error "asdf") - """; + from Standard.Base import Integer, Warning, Error + import Standard.Base.Errors.Illegal_Argument.Illegal_Argument + from Standard.Base.Errors.Common import Out_Of_Range + + err_warn -> Integer ! Illegal_Argument = + v = Warning.attach (Out_Of_Range.Error "qewr") 12 + case v of + _ : Integer -> Error.throw (Illegal_Argument.Error "asdf") + """; var module = ctxRule.eval(LanguageInfo.ID, code); var errorWithWarning = module.invokeMember(MethodNames.Module.EVAL_EXPRESSION, "err_warn"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/AssertionsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/AssertionsTest.java index b6b4c859f286..82b839bde916 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/AssertionsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/AssertionsTest.java @@ -47,9 +47,9 @@ public void simpleAssertionFailureWithMessage() { try { ctxRule.evalModule( """ - from Standard.Base import False, Runtime - main = Runtime.assert False - """); + from Standard.Base import False, Runtime + main = Runtime.assert False + """); fail("Should throw Assertion_Error"); } catch (PolyglotException e) { assertThat(e.getGuestObject().isException(), is(true)); @@ -61,9 +61,9 @@ public void assertionFailureDisplaysMessage() { try { ctxRule.evalModule( """ - from Standard.Base import False, Runtime - main = Runtime.assert False 'My fail message' - """); + from Standard.Base import False, Runtime + main = Runtime.assert False 'My fail message' + """); fail("Should throw Assertion_Error"); } catch (PolyglotException e) { assertThat( @@ -77,10 +77,10 @@ public void assertionFailureDisplaysStackTrace() { try { ctxRule.evalModule( """ - from Standard.Base import False, Runtime - foo = Runtime.assert False 'My fail message' - main = foo - """); + from Standard.Base import False, Runtime + foo = Runtime.assert False 'My fail message' + main = foo + """); fail("Should throw Assertion_Error"); } catch (PolyglotException e) { assertThat(e.getStackTrace().length, greaterThan(5)); @@ -97,9 +97,9 @@ public void assertionSuccessReturnsNothing() { Value res = ctxRule.evalModule( """ - from Standard.Base import Runtime, True - main = Runtime.assert True - """); + from Standard.Base import Runtime, True + main = Runtime.assert True + """); assertTrue(res.isNull()); } @@ -108,9 +108,9 @@ public void assertChecksTypeOfReturnValue() { try { ctxRule.evalModule( """ - from Standard.Base import Runtime - main = Runtime.assert [1,2,3] - """); + from Standard.Base import Runtime + main = Runtime.assert [1,2,3] + """); fail("Should throw Type_Error"); } catch (PolyglotException e) { assertThat(e.getMessage(), stringContainsInOrder(List.of("Type", "error"))); @@ -122,14 +122,14 @@ public void actionInAssertIsComputedWhenAssertionsAreEnabled() { Value res = ctxRule.evalModule( """ - from Standard.Base import Runtime - import Standard.Base.Runtime.Ref.Ref + from Standard.Base import Runtime + import Standard.Base.Runtime.Ref.Ref - main = - ref = Ref.new 10 - Runtime.assert (ref.put 23 . is_nothing . not) - ref.get - """); + main = + ref = Ref.new 10 + Runtime.assert (ref.put 23 . is_nothing . not) + ref.get + """); assertTrue(res.isNumber()); assertThat(res.asInt(), is(23)); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/DisabledAssertionsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/DisabledAssertionsTest.java index 6b687dab5863..94c02cf04525 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/DisabledAssertionsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/DisabledAssertionsTest.java @@ -27,7 +27,7 @@ public void assertionsCanBeDisabledWithEnvVar() { public void actionInAssertIsNotComputedWhenAssertionsAreDisabled() { Value res = ctxRule.evalModule( - """ +""" from Standard.Base import Runtime import Standard.Base.Runtime.Ref.Ref diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/SuccessfulAssertionExpressionTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/SuccessfulAssertionExpressionTest.java index 4eda201009d8..989a353becac 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/SuccessfulAssertionExpressionTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/asserts/SuccessfulAssertionExpressionTest.java @@ -21,7 +21,7 @@ public class SuccessfulAssertionExpressionTest { .build(); private static final String imports = - """ +""" from Standard.Base import all polyglot java import java.lang.System as Java_System diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/builtins/InvokeBuiltinMethodViaInteropTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/builtins/InvokeBuiltinMethodViaInteropTest.java index 6350b31c9194..bd80e17a9804 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/builtins/InvokeBuiltinMethodViaInteropTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/builtins/InvokeBuiltinMethodViaInteropTest.java @@ -71,7 +71,8 @@ public void invokePathMethodOnFile() { @Test public void invokeToTextOnVector() { - var code = """ + var code = + """ main = [1,2,3] """; var vec = ctxRule.evalModule(code); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConstructorTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConstructorTest.java index bf7bb4ec82b2..5e0c5705fdd1 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConstructorTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConstructorTest.java @@ -27,17 +27,17 @@ public void exportedConstructorsAreInBindingMap() throws IOException { new SourceModule( QualifiedName.fromString("Boolean"), """ - type Boolean - True - False - """); + type Boolean + True + False + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Boolean.Boolean.True - export project.Boolean.Boolean.False - """); + export project.Boolean.Boolean.True + export project.Boolean.Boolean.False + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(booleanMod, mainMod), projDir); @@ -56,19 +56,19 @@ public void constructorsCanBeExportedFromTheSameModule() throws IOException { new SourceModule( QualifiedName.fromString("Boolean"), """ - export project.Boolean.Boolean.True - export project.Boolean.Boolean.False - type Boolean - True - False - """); + export project.Boolean.Boolean.True + export project.Boolean.Boolean.False + type Boolean + True + False + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - # Import just the module on purpose - import project.Boolean - """); + # Import just the module on purpose + import project.Boolean + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(booleanMod, mainMod), projDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConversionMethodTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConversionMethodTest.java index 6a4727aa6efb..493f68708053 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConversionMethodTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportConversionMethodTest.java @@ -29,24 +29,25 @@ public void conversionMethodCanBeImportedByName() throws IOException { new SourceModule( QualifiedName.fromString("A_Module"), """ - type A_Type - Value - type B_Type - """); + type A_Type + Value + type B_Type + """); var bMod = new SourceModule( QualifiedName.fromString("B_Module"), """ - import project.A_Module.A_Type - import project.A_Module.B_Type + import project.A_Module.A_Type + import project.A_Module.B_Type - B_Type.from (_:A_Type) = 42 - """); + B_Type.from (_:A_Type) = 42 + """); var mainMod = new SourceModule( - QualifiedName.fromString("Main"), """ - import project.B_Module.from - """); + QualifiedName.fromString("Main"), + """ + import project.B_Module.from + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, bMod, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -67,15 +68,16 @@ public void conversionMethodIsInBindingMap() throws IOException { new SourceModule( QualifiedName.fromString("A_Module"), """ - type A_Type - type B_Type - B_Type.from (_:A_Type) = 42 - """); + type A_Type + type B_Type + B_Type.from (_:A_Type) = 42 + """); var mainMod = new SourceModule( - QualifiedName.fromString("Main"), """ - export project.A_Module.from - """); + QualifiedName.fromString("Main"), + """ + export project.A_Module.from + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); @@ -105,16 +107,17 @@ public void multipleConversionMethodsCanBeImported() throws IOException { new SourceModule( QualifiedName.fromString("A_Module"), """ - type A_Type - type B_Type - B_Type.from (_:A_Type) = 1 - A_Type.from (_:B_Type) = 2 - """); + type A_Type + type B_Type + B_Type.from (_:A_Type) = 1 + A_Type.from (_:B_Type) = 2 + """); var mainMod = new SourceModule( - QualifiedName.fromString("Main"), """ - export project.A_Module.from - """); + QualifiedName.fromString("Main"), + """ + export project.A_Module.from + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportExtensionMethodTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportExtensionMethodTest.java index d64df56ed6f2..f5970c6d09c1 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportExtensionMethodTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportExtensionMethodTest.java @@ -27,26 +27,26 @@ public void extensionMethodCanBeExportedByName() throws IOException { new SourceModule( QualifiedName.fromString("T_Module"), """ - type My_Type - Value x - My_Type.extension_method self = self.x - """); + type My_Type + Value x + My_Type.extension_method self = self.x + """); var aMod = new SourceModule( QualifiedName.fromString("A_Module"), """ - export project.T_Module.My_Type - export project.T_Module.extension_method - """); + export project.T_Module.My_Type + export project.T_Module.extension_method + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.A_Module import all - main = - obj = My_Type.Value 42 - obj.extension_method - """); + from project.A_Module import all + main = + obj = My_Type.Value 42 + obj.extension_method + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, aMod, mainMod), projDir); ProjectUtils.testProjectRun( @@ -63,31 +63,31 @@ public void multipleExtensionMethodsCanBeExportedByName() throws IOException { new SourceModule( QualifiedName.fromString("T_Module"), """ - type My_Type - Value x - type My_Other_Type - Value y - My_Type.extension_method self = self.x - My_Other_Type.extension_method self = self.y - """); + type My_Type + Value x + type My_Other_Type + Value y + My_Type.extension_method self = self.x + My_Other_Type.extension_method self = self.y + """); var aMod = new SourceModule( QualifiedName.fromString("A_Module"), """ - export project.T_Module.My_Type - export project.T_Module.My_Other_Type - export project.T_Module.extension_method - """); + export project.T_Module.My_Type + export project.T_Module.My_Other_Type + export project.T_Module.extension_method + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.A_Module import all - main = - t = My_Type.Value 42 - ot = My_Other_Type.Value 42 - t.extension_method == ot.extension_method - """); + from project.A_Module import all + main = + t = My_Type.Value 42 + ot = My_Other_Type.Value 42 + t.extension_method == ot.extension_method + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, aMod, mainMod), projDir); ProjectUtils.testProjectRun( @@ -104,17 +104,17 @@ public void extensionMethodIsInBindingMap() throws IOException { new SourceModule( QualifiedName.fromString("T_Module"), """ - type My_Type - Value x - My_Type.extension_method self = self.x - """); + type My_Type + Value x + My_Type.extension_method self = self.x + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.T_Module.My_Type - export project.T_Module.extension_method - """); + export project.T_Module.My_Type + export project.T_Module.extension_method + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -133,10 +133,10 @@ public void extensionMethodIsDefinedEntity() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - type My_Type - Value x - My_Type.extension_method self = self.x - """); + type My_Type + Value x + My_Type.extension_method self = self.x + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportModuleTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportModuleTest.java index f68035294b0f..36fca7816111 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportModuleTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportModuleTest.java @@ -27,20 +27,20 @@ public void exportSubModuleFromExistingModule() throws IOException { new SourceModule( QualifiedName.fromString("Module.SubModule"), """ - # Blank on purpose - """); + # Blank on purpose + """); var module = new SourceModule( QualifiedName.fromString("Module"), """ - # Blank on purpose - ensures that `Module` is not just synthetic - """); + # Blank on purpose - ensures that `Module` is not just synthetic + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Module.SubModule - """); + export project.Module.SubModule + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(subModule, module, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -61,14 +61,14 @@ public void exportSubModuleFromSyntheticModule() throws IOException { new SourceModule( QualifiedName.fromString("Module.SubModule"), """ - # Blank on purpose - """); + # Blank on purpose + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Module.SubModule - """); + export project.Module.SubModule + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(subModule, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportResolutionOrderingTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportResolutionOrderingTest.java index f275070e647b..15057f5630b6 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportResolutionOrderingTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportResolutionOrderingTest.java @@ -37,14 +37,14 @@ public void testOrderingWithSubmoduleOfSyntheticModule() throws IOException { new SourceModule( QualifiedName.fromString("Synthetic_Module.A_Module"), """ - type A_Type - """); + type A_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Synthetic_Module.A_Module.A_Type - """); + export project.Synthetic_Module.A_Module.A_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); @@ -68,21 +68,21 @@ public void testOrderingWithTwoSubmodulesOfSyntheticModule() throws IOException new SourceModule( QualifiedName.fromString("Synthetic_Module.A_Module"), """ - type A_Type - """); + type A_Type + """); var bMod = new SourceModule( QualifiedName.fromString("Synthetic_Module.B_Module"), """ - type B_Type - """); + type B_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Synthetic_Module.A_Module.A_Type - export project.Synthetic_Module.B_Module.B_Type - """); + export project.Synthetic_Module.A_Module.A_Type + export project.Synthetic_Module.B_Module.B_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, bMod, mainMod), projDir); @@ -111,15 +111,16 @@ public void testOrderingWithTwoSubmodulesOfSyntheticModule() throws IOException public void testOrderingWithTwoSyntheticModules() throws IOException { var aMod = new SourceModule( - QualifiedName.fromString("Syn_1.Syn_2.A_Module"), """ - type A_Type - """); + QualifiedName.fromString("Syn_1.Syn_2.A_Module"), + """ + type A_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.Syn_1.Syn_2.A_Module.A_Type - """); + export project.Syn_1.Syn_2.A_Module.A_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportStaticMethodTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportStaticMethodTest.java index 74e87e0aeb60..960dfd564395 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportStaticMethodTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/exports/ExportStaticMethodTest.java @@ -24,23 +24,24 @@ public class ExportStaticMethodTest { public void staticMethodCanBeExportedByName() throws IOException { var tMod = new SourceModule( - QualifiedName.fromString("T_Module"), """ - static_method x = x - """); + QualifiedName.fromString("T_Module"), + """ + static_method x = x + """); var aMod = new SourceModule( QualifiedName.fromString("A_Module"), """ - export project.T_Module.static_method - """); + export project.T_Module.static_method + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.A_Module import all - main = - static_method 42 - """); + from project.A_Module import all + main = + static_method 42 + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, aMod, mainMod), projDir); @@ -58,18 +59,18 @@ public void staticAndModuleMethodsWithSameNameCanBeImported() throws IOException new SourceModule( QualifiedName.fromString("T_Module"), """ - type My_Type + type My_Type + method x = x method x = x - method x = x - """); + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.T_Module import My_Type, method - main = - My_Type.method 42 == method 42 - """); + from project.T_Module import My_Type, method + main = + My_Type.method 42 == method 42 + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, mainMod), projDir); @@ -85,15 +86,16 @@ public void staticAndModuleMethodsWithSameNameCanBeImported() throws IOException public void moduleMethodIsInBindingMap() throws IOException { var tMod = new SourceModule( - QualifiedName.fromString("T_Module"), """ - module_method x = x - """); + QualifiedName.fromString("T_Module"), + """ + module_method x = x + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.T_Module.module_method - """); + export project.T_Module.module_method + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, mainMod), projDir); @@ -112,15 +114,15 @@ public void staticMethodIsInBindingMap() throws IOException { new SourceModule( QualifiedName.fromString("T_Module"), """ - type My_Type - My_Type.static_method x = x - """); + type My_Type + My_Type.static_method x = x + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.T_Module.static_method - """); + export project.T_Module.static_method + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(tMod, mainMod), projDir); @@ -137,9 +139,10 @@ public void staticMethodIsInBindingMap() throws IOException { public void staticMethodIsDefinedEntity() throws IOException { var mainMod = new SourceModule( - QualifiedName.fromString("Main"), """ - static_method x = x - """); + QualifiedName.fromString("Main"), + """ + static_method x = x + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/hash/HashCodeTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/hash/HashCodeTest.java index b6462a66db91..83865544c419 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/hash/HashCodeTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/hash/HashCodeTest.java @@ -110,9 +110,9 @@ public void hashCodeContractTheory(Object firstValue, Object secondValue) { assertEquals( String.format( """ - If two objects are same, they should have same hash codes: - firstVal = %s, secondVal = %s, firstHash = %d, secondHash = %d - """, + If two objects are same, they should have same hash codes: + firstVal = %s, secondVal = %s, firstHash = %d, secondHash = %d + """, interop.toDisplayString(firstValue), interop.toDisplayString(secondValue), firstHash, diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/imports/ImportSymbolsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/imports/ImportSymbolsTest.java index b76f6c2da9da..a930b6b6f088 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/imports/ImportSymbolsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/imports/ImportSymbolsTest.java @@ -28,17 +28,18 @@ public class ImportSymbolsTest { public void importAllFromModuleDoesNotImportModuleItself() throws IOException { var aMod = new SourceModule( - QualifiedName.fromString("A_module"), """ - a_mod_method x = x - """); + QualifiedName.fromString("A_module"), + """ + a_mod_method x = x + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.A_module import all - main = - A_Module.a_mod_method 42 - """); + from project.A_module import all + main = + A_Module.a_mod_method 42 + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -58,17 +59,17 @@ public void importAllFromTypeDoesNotImportTypeItself() throws IOException { new SourceModule( QualifiedName.fromString("A_module"), """ - type A_Type - Cons - """); + type A_Type + Cons + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.A_module.A_Type import all - main = - A_Type.Cons - """); + from project.A_module.A_Type import all + main = + A_Type.Cons + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { @@ -87,21 +88,23 @@ public void importAllFromTypeDoesNotImportTypeItself() throws IOException { @Test public void importEntityFromModuleThatExportsItFromOtherModule() throws IOException { var aMod = - new SourceModule(QualifiedName.fromString("A_Module"), """ - type A_Type - """); + new SourceModule( + QualifiedName.fromString("A_Module"), + """ + type A_Type + """); var bMod = new SourceModule( QualifiedName.fromString("B_Module"), """ - export project.A_Module.A_Type - """); + export project.A_Module.A_Type + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - import project.B_Module.A_Type - """); + import project.B_Module.A_Type + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, bMod, mainMod), projDir); try (var ctx = ContextUtils.newBuilder().withProjectRoot(projDir).build()) { diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/AvoidIdInstrumentationTagTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/AvoidIdInstrumentationTagTest.java index 9f020df378f1..4eb2bc68d6d0 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/AvoidIdInstrumentationTagTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/AvoidIdInstrumentationTagTest.java @@ -52,11 +52,11 @@ public static void disposeContext() { public void avoidIdInstrumentationInLambdaMapFunctionWithFloor() throws Exception { var code = """ - from Standard.Base import all - import Standard.Visualization + from Standard.Base import all + import Standard.Visualization - run n = 0.up_to n . map i-> 1.floor * i - """; + run n = 0.up_to n . map i-> 1.floor * i + """; var src = Source.newBuilder("enso", code, "TestLambda.enso").build(); var module = ctxRule.eval(src); var run = module.invokeMember("eval_expression", "run"); @@ -78,11 +78,11 @@ public void avoidIdInstrumentationInLambdaMapFunctionWithFloor() throws Exceptio public void avoidIdInstrumentationInLambdaMapFunctionYear2010() throws Exception { var code = """ - from Standard.Base import all + from Standard.Base import all - operator13 = [ 1973, 1975, 2005, 2006 ] - operator15 = operator13.map year-> if year < 2000 then [255, 100] else if year < 2010 then [0, 255] else [0, 100] - """; + operator13 = [ 1973, 1975, 2005, 2006 ] + operator15 = operator13.map year-> if year < 2000 then [255, 100] else if year < 2010 then [0, 255] else [0, 100] + """; var src = Source.newBuilder("enso", code, "YearLambda.enso").build(); var module = ctxRule.eval(src); var res = module.invokeMember("eval_expression", "operator15"); @@ -108,14 +108,14 @@ public void avoidIdInstrumentationInLambdaMapFunctionYear2010() throws Exception public void avoidIdInstrumentationInMap() throws Exception { var code = """ - from Standard.Base import all - - run = - operator1 = [ "FooBar", "whateveR" ] - fun1 = _.to_case Case.Lower - operator2 = operator1.map fun1 - operator2 - """; + from Standard.Base import all + + run = + operator1 = [ "FooBar", "whateveR" ] + fun1 = _.to_case Case.Lower + operator2 = operator1.map fun1 + operator2 + """; var src = Source.newBuilder("enso", code, "CaseLambda.enso").build(); var module = ctxRule.eval(src); var res = module.invokeMember("eval_expression", "run"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/FunctionPointerTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/FunctionPointerTest.java index 67538540541c..21392acf6cab 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/FunctionPointerTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/FunctionPointerTest.java @@ -17,7 +17,8 @@ public class FunctionPointerTest { @Test public void moduleFunctionPointer() throws Exception { - var rawCode = """ + var rawCode = + """ from Standard.Base import all run a b = a + b diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/IncrementalUpdatesTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/IncrementalUpdatesTest.java index e180b0193991..cc5db6f121e9 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/IncrementalUpdatesTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/IncrementalUpdatesTest.java @@ -210,16 +210,16 @@ private static String extractPositions( var code = extractPositions( """ - import Standard.Base.IO - - &$foo$ = - x = #{originalText}# - *x* - & - main = - y = @foo@ - %IO.println y% - """ + import Standard.Base.IO + + &$foo$ = + x = #{originalText}# + *x* + & + main = + y = @foo@ + %IO.println y% + """ .replace("{originalText}", originalText), "&$#*@%", pos); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/InsightForEnsoTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/InsightForEnsoTest.java index 6e3715603f64..c69288c4b415 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/InsightForEnsoTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/InsightForEnsoTest.java @@ -42,18 +42,18 @@ public static void initContext() { Source.newBuilder( "js", """ - insight.on('enter', (ctx, frame) => { - print(`${ctx.name} at ${ctx.source.name}:${ctx.line}:`); - let dump = ""; - for (let p in frame) { - frame.unknown // used to yield NullPointerException - dump += ` ${p}=${frame[p]}`; - } - print(dump); - }, { - roots : true - }); - """, + insight.on('enter', (ctx, frame) => { + print(`${ctx.name} at ${ctx.source.name}:${ctx.line}:`); + let dump = ""; + for (let p in frame) { + frame.unknown // used to yield NullPointerException + dump += ` ${p}=${frame[p]}`; + } + print(dump); + }, { + roots : true + }); + """, "trace.js") .build(); } catch (IOException e) { diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeProgressTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeProgressTest.java index 4be16ac471da..06cc45132f06 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeProgressTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeProgressTest.java @@ -66,18 +66,18 @@ public void reportAProgress() { var code = """ - import Standard.Base.Logging.Progress + import Standard.Base.Logging.Progress - main = - res = steps - res + main = + res = steps + res - steps = Progress.run "Six steps" 6 progress-> - progress.advance 1 - progress.advance 2 - progress.advance 3 - 10 - """; + steps = Progress.run "Six steps" 6 progress-> + progress.advance 1 + progress.advance 2 + progress.advance 3 + 10 + """; metadata.assertInCode(mainRes, code, "steps"); var contents = metadata.appendToCode(code); @@ -135,19 +135,19 @@ public void reportAbitOfProgressAndMessage() { var code = """ - import Standard.Base.Logging.Progress - - main = - res = steps - res - - steps = Progress.run "Few steps" 5 progress-> - progress.advance - progress.log "I've just finished 1st step" - progress.advance 3 - progress.log "Returning a value" - 42 - """; + import Standard.Base.Logging.Progress + + main = + res = steps + res + + steps = Progress.run "Few steps" 5 progress-> + progress.advance + progress.log "I've just finished 1st step" + progress.advance 3 + progress.log "Returning a value" + 42 + """; metadata.assertInCode(mainRes, code, "steps"); var contents = metadata.appendToCode(code); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeServerTesting.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeServerTesting.java index f22be9496a0f..05467d4d9277 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeServerTesting.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/RuntimeServerTesting.java @@ -36,20 +36,20 @@ static void accessRuntimeCache(TestContext context) { var code = """ - from Standard.Base.Runtime import value_for_uuid - from Standard.Base.Data.Numbers import all - import Standard.Base.IO + from Standard.Base.Runtime import value_for_uuid + from Standard.Base.Data.Numbers import all + import Standard.Base.IO - private v n = value_for_uuid n + private v n = value_for_uuid n - main = - x_0 = 6 - x_1 = 7 - x_2 = (v "${aa}")*(v "${bb}") - IO.println x_2 - IO.println x_0*x_1 - IO.println x_2==x_0*x_1 - """ + main = + x_0 = 6 + x_1 = 7 + x_2 = (v "${aa}")*(v "${bb}") + IO.println x_2 + IO.println x_0*x_1 + IO.println x_2==x_0*x_1 + """ .replace("${aa}", id_x_0.toString()) .replace("${bb}", id_x_1.toString()); var contents = metadata.appendToCode(code); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/WarningInstrumentationTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/WarningInstrumentationTest.java index 9c2f1c170c5f..2e9f4a924b9e 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/WarningInstrumentationTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/instrument/WarningInstrumentationTest.java @@ -60,16 +60,16 @@ public void instrumentValueWithWarnings() throws Exception { var idOp3 = metadata.addItem(239, 13, null); var rawCode = """ - from Standard.Base import all - from Standard.Base.Warning import Warning - from Standard.Table import Table + from Standard.Base import all + from Standard.Base.Warning import Warning + from Standard.Table import Table - run column_name = - operator1 = Table.new [[column_name, [1,2,3]]] - operator2 = Warning.attach "Text" operator1 - operator3 = operator2.get - operator3 - """; + run column_name = + operator1 = Table.new [[column_name, [1,2,3]]] + operator2 = Warning.attach "Text" operator1 + operator3 = operator2.get + operator3 + """; var code = metadata.appendToCode(rawCode); var src = Source.newBuilder("enso", code, "TestWarning.enso").build(); var module = ctxRule.eval(src); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/AtomInteropTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/AtomInteropTest.java index ad74052f5b49..35f84bf57afe 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/AtomInteropTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/AtomInteropTest.java @@ -38,14 +38,14 @@ public void atomMemberNames_AreNotQualified() { var myTypeAtom = ctxRule.evalModule( """ - import Standard.Base.Any.Any + import Standard.Base.Any.Any - type My_Type - Cons field_1 field_2 + type My_Type + Cons field_1 field_2 - main = - My_Type.Cons 1 2 - """); + main = + My_Type.Cons 1 2 + """); assertThat(myTypeAtom.hasMembers(), is(true)); var memberNames = myTypeAtom.getMemberKeys(); assertThat("Member names are not qualified", memberNames, hasItem(not(containsString(".")))); @@ -56,12 +56,12 @@ public void atomMembersAreConstructorFields_SingleConstructor() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons field_1 field_2 + type My_Type + Cons field_1 field_2 - main = - My_Type.Cons 1 2 - """); + main = + My_Type.Cons 1 2 + """); assertThat(myTypeAtom.hasMembers(), is(true)); var memberNames = myTypeAtom.getMemberKeys(); assertThat("Has more than two fields", memberNames.size(), is(greaterThan(2))); @@ -77,12 +77,12 @@ public void atomIsNotMetaObject() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons field_1 field_2 + type My_Type + Cons field_1 field_2 - main = - My_Type.Cons 1 2 - """); + main = + My_Type.Cons 1 2 + """); assertThat(myTypeAtom.isMetaObject(), is(false)); assertThat(myTypeAtom.getMetaObject().getMetaSimpleName(), is("My_Type")); } @@ -92,11 +92,11 @@ public void typeHasAnyAsSuperType() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons + type My_Type + Cons - main = My_Type.Cons - """); + main = My_Type.Cons + """); var myType = myTypeAtom.getMetaObject(); assertThat(myType.hasMetaParents(), is(true)); var metaParents = myType.getMetaParents(); @@ -111,13 +111,13 @@ public void atomMembersAreConstructorFields_ManyConstructors() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons_1 f1 f2 f3 f4 f5 f6 - Cons_2 g1 g2 g3 - Cons_3 h1 h2 h3 h4 h5 h6 h7 h8 h9 + type My_Type + Cons_1 f1 f2 f3 f4 f5 f6 + Cons_2 g1 g2 g3 + Cons_3 h1 h2 h3 h4 h5 h6 h7 h8 h9 - main = My_Type.Cons_2 "g1" "g2" "g3" - """); + main = My_Type.Cons_2 "g1" "g2" "g3" + """); assertThat( "Member names correspond to constructor field names for a single constructor", myTypeAtom.getMemberKeys(), @@ -129,12 +129,12 @@ public void methodIsAtomMember() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a b - method self = 42 + type My_Type + Cons a b + method self = 42 - main = My_Type.Cons "a" "b" - """); + main = My_Type.Cons "a" "b" + """); assertThat("Method is a member of the atom", myTypeAtom.getMemberKeys(), hasItem("method")); assertThat("method is an invokable member", myTypeAtom.canInvokeMember("method"), is(true)); } @@ -144,12 +144,12 @@ public void methodIsAtomMember_InteropLibrary() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a b - method self = 42 + type My_Type + Cons a b + method self = 42 - main = My_Type.Cons "a" "b" - """); + main = My_Type.Cons "a" "b" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat("Atom has members", interop.hasMembers(atom), is(true)); @@ -163,11 +163,11 @@ public void fieldsFromPrivateConstructorAreInternalMembers() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - private Cons a + type My_Type + private Cons a - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat("field a is internal", interop.isMemberInternal(atom, "a"), is(true)); @@ -182,11 +182,11 @@ public void fieldFromPrivateConstructorIsReadable() var myTypeAtom = ctxRule.evalModule( """ - type My_Type - private Cons a + type My_Type + private Cons a - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat( @@ -212,13 +212,13 @@ public void allMethodsAreInternalMembers() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a - pub_method self = 42 - private priv_method self = 42 + type My_Type + Cons a + pub_method self = 42 + private priv_method self = 42 - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat( @@ -239,11 +239,11 @@ public void internalMembersIncludeMethodsFromAny_WithoutImport() throws Exceptio var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a + type My_Type + Cons a - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var memberNames = getAllMemberNames(atom); var anyBuiltinMethods = ctxRule.builtinMethodsFromAny(); @@ -261,13 +261,13 @@ public void internalMembersIncludeMethodsFromAny_WithImport() throws Exception { var myTypeAtom = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type My_Type - Cons a + type My_Type + Cons a - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var memberNames = getAllMemberNames(atom); var anyMethods = ctxRule.allMethodsFromAny(); @@ -282,13 +282,13 @@ public void allMembersAreReadableAndInvocable() var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a - pub_method self = 42 - private priv_method self = 42 + type My_Type + Cons a + pub_method self = 42 + private priv_method self = 42 - main = My_Type.Cons "a" - """); + main = My_Type.Cons "a" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); var members = interop.getMembers(atom, true); @@ -310,12 +310,12 @@ public void constructorIsNotAtomMember() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a b - method self = 42 + type My_Type + Cons a b + method self = 42 - main = My_Type.Cons "a" "b" - """); + main = My_Type.Cons "a" "b" + """); assertThat("Cons is not atom member", myTypeAtom.getMemberKeys(), not(hasItem("Cons"))); } @@ -328,11 +328,11 @@ public void fieldIsInvocable() var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a b + type My_Type + Cons a b - main = My_Type.Cons 1 2 - """); + main = My_Type.Cons 1 2 + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat("Field a is invocable", interop.isMemberInvocable(atom, "a"), is(true)); @@ -346,11 +346,11 @@ public void fieldIsReadable() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a + type My_Type + Cons a - main = My_Type.Cons 1 - """); + main = My_Type.Cons 1 + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat("Field a is readable", interop.isMemberReadable(atom, "a"), is(true)); @@ -361,12 +361,12 @@ public void staticMethodIsNotAtomMember() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons - static_method = 42 + type My_Type + Cons + static_method = 42 - main = My_Type.Cons - """); + main = My_Type.Cons + """); assertThat( "Static method is not atom member", myTypeAtom.getMemberKeys(), @@ -378,12 +378,12 @@ public void constructorIsNotAtomMember_InteropLibrary() { var myTypeAtom = ctxRule.evalModule( """ - type My_Type - Cons a b - method self = 42 + type My_Type + Cons a b + method self = 42 - main = My_Type.Cons "a" "b" - """); + main = My_Type.Cons "a" "b" + """); var atom = ctxRule.unwrapValue(myTypeAtom); var interop = InteropLibrary.getUncached(); assertThat("Cons is not atom member", interop.isMemberExisting(atom, "Cons"), is(false)); @@ -394,12 +394,12 @@ public void typeMembersAreConstructors() { var myType = ctxRule.evalModule( """ - type My_Type - Cons_1 - Cons_2 + type My_Type + Cons_1 + Cons_2 - main = My_Type - """); + main = My_Type + """); assertThat("type has constructors as members", myType.hasMembers(), is(true)); assertThat(myType.getMemberKeys(), containsInAnyOrder("Cons_1", "Cons_2")); assertThat( @@ -417,18 +417,18 @@ public void invokeLazyField_DoesNotCauseStackOverflow() var atom = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type Generator - Value n ~next + type Generator + Value n ~next - natural = - gen n = Generator.Value n (gen n+1) - gen 2 + natural = + gen n = Generator.Value n (gen n+1) + gen 2 - main = - natural - """); + main = + natural + """); var atomUnwrapped = ctxRule.unwrapValue(atom); var interop = InteropLibrary.getUncached(); var next = interop.invokeMember(atomUnwrapped, "next"); @@ -440,18 +440,18 @@ public void invokeVsReadAndExecute() throws Exception { var atom = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type Generator - Value n ~next + type Generator + Value n ~next - ahead self n = if n <= 1 then self.next else - @Tail_Call self.next.ahead n-1 + ahead self n = if n <= 1 then self.next else + @Tail_Call self.next.ahead n-1 - main = - gen n = Generator.Value n (gen n+1) - gen 2 - """); + main = + gen n = Generator.Value n (gen n+1) + gen 2 + """); var atomUnwrapped = ctxRule.unwrapValue(atom); var interop = InteropLibrary.getUncached(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JavaInteropTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JavaInteropTest.java index 6b38dc98e46a..0a1cc7c6e384 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JavaInteropTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JavaInteropTest.java @@ -318,25 +318,25 @@ public void testImportOuterClassAndAccessNestedInnerClass() { public void testToStringBehavior() { var code = """ - from Standard.Base import all + from Standard.Base import all - polyglot java import org.enso.example.ToString as Foo + polyglot java import org.enso.example.ToString as Foo - type My_Fooable_Implementation - Instance x + type My_Fooable_Implementation + Instance x - foo : Integer - foo self = 100+self.x + foo : Integer + foo self = 100+self.x - main = - fooable = My_Fooable_Implementation.Instance 23 - a = fooable.foo - b = fooable.to_text - c = Foo.callFoo fooable - d = Foo.showObject fooable - e = Foo.callFooAndShow fooable - [a, b, c, d, e] - """; + main = + fooable = My_Fooable_Implementation.Instance 23 + a = fooable.foo + b = fooable.to_text + c = Foo.callFoo fooable + d = Foo.showObject fooable + e = Foo.callFooAndShow fooable + [a, b, c, d, e] + """; var res = ctx().evalModule(code); assertTrue("It is an array", res.hasArrayElements()); @@ -352,21 +352,21 @@ public void testToStringBehavior() { public void testToStringBehaviorSimple1() { var code = """ - from Standard.Base import all + from Standard.Base import all - polyglot java import org.enso.example.ToString as Foo + polyglot java import org.enso.example.ToString as Foo - type My_Fooable_Implementation - Instance x + type My_Fooable_Implementation + Instance x - foo : Integer - foo self = 100+self.x + foo : Integer + foo self = 100+self.x - main = - fooable = My_Fooable_Implementation.Instance 23 - e = Foo.callFooAndShow fooable - e - """; + main = + fooable = My_Fooable_Implementation.Instance 23 + e = Foo.callFooAndShow fooable + e + """; var res = ctx().evalModule(code); assertEquals("{(Instance 23)}.foo() = 123", res.asString()); @@ -376,13 +376,13 @@ public void testToStringBehaviorSimple1() { public void throwsParsingError() { var code = """ - from Standard.Base import Panic - polyglot java import java.lang.Integer as Num - polyglot java import java.lang.NumberFormatException as Ex + from Standard.Base import Panic + polyglot java import java.lang.Integer as Num + polyglot java import java.lang.NumberFormatException as Ex - main = - Panic.catch Ex (Num.parseInt "NotAnInt") .payload - """; + main = + Panic.catch Ex (Num.parseInt "NotAnInt") .payload + """; var res = ctx().evalModule(code); assertTrue("Got an exception back", res.isException()); @@ -399,20 +399,20 @@ Panic.catch Ex (Num.parseInt "NotAnInt") .payload public void throwsParsingErrorIndirect() { var code = """ - from Standard.Base import Panic - polyglot java import java.lang.Integer as Num - polyglot java import java.lang.NumberFormatException as Ex - polyglot java import org.enso.example.TestClass + from Standard.Base import Panic + polyglot java import java.lang.Integer as Num + polyglot java import java.lang.NumberFormatException as Ex + polyglot java import org.enso.example.TestClass - type En - Err msg + type En + Err msg - main = - e = TestClass.newDirectExecutor - e.execute - Panic.catch Ex (Num.parseInt "NotAnInt") ex-> - Panic.throw (En.Err ex.payload.to_text) - """; + main = + e = TestClass.newDirectExecutor + e.execute + Panic.catch Ex (Num.parseInt "NotAnInt") ex-> + Panic.throw (En.Err ex.payload.to_text) + """; try { var res = ctx().evalModule(code); @@ -506,21 +506,21 @@ public void catchCheckedSubExceptionThrownInJava() { private Value checkedException(int t) { var code = """ - polyglot java import org.enso.example.TestException - from Standard.Base import Panic + polyglot java import org.enso.example.TestException + from Standard.Base import Panic - handle_errors ~action = - Panic.catch TestException action caught_panic-> - -1 + handle_errors ~action = + Panic.catch TestException action caught_panic-> + -1 - run t = case t of - 0 -> handle_errors 10 - 1 -> handle_errors (Panic.throw TestException.new) - 2 -> handle_errors (TestException.throwMe) - 3 -> handle_errors (TestException.throwSubtype) + run t = case t of + 0 -> handle_errors 10 + 1 -> handle_errors (Panic.throw TestException.new) + 2 -> handle_errors (TestException.throwMe) + 3 -> handle_errors (TestException.throwSubtype) - main = run - """; + main = run + """; var result = ctx().evalModule(code); return result.execute(t); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JsInteropTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JsInteropTest.java index 8937be9f9a7b..5afdc5377be4 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JsInteropTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/JsInteropTest.java @@ -14,17 +14,17 @@ public class JsInteropTest { public void testDefaultJSPrint() { var src = """ - from Standard.Base import Json + from Standard.Base import Json - main = - json = Json.parse <| ''' - { - "inner": { - "a": 1 + main = + json = Json.parse <| ''' + { + "inner": { + "a": 1 + } } - } - json.get "inner" - """; + json.get "inner" + """; Value res = ctxRule.evalModule(src); assertEquals("{\"a\":1}", res.toString()); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaObjectTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaObjectTest.java index 6d3d085dc5a9..e576e08521aa 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaObjectTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaObjectTest.java @@ -91,13 +91,13 @@ public void checkingAtomMetaObject() throws Exception { Source.newBuilder( "enso", """ - type Atm - Data x - End + type Atm + Data x + End - data = Atm.Data 5 - end = Atm.End - """, + data = Atm.Data 5 + end = Atm.End + """, "atom_test.enso") .uri(uri) .buildLiteral(); @@ -254,7 +254,7 @@ public void nothingIsNotMeta() { @Test public void nothingWithWarningIsNotMeta() { var src = - """ +""" import Standard.Base.Warning.Warning import Standard.Base.Nothing.Nothing @@ -266,7 +266,8 @@ public void nothingWithWarningIsNotMeta() { @Test public void nothingShouldBeNull() { - var src = """ + var src = +""" import Standard.Base.Nothing.Nothing main = Nothing """; @@ -451,11 +452,11 @@ private void checkAllTypesSatisfy(Check check) throws Exception { continue; } switch (t.getMetaSimpleName()) { - // represented as primitive values without meta object + // represented as primitive values without meta object case "Float" -> {} - // has no instances + // has no instances case "Array_Proxy" -> {} - // Warning is transparent and invisible + // Warning is transparent and invisible case "Warning" -> {} default -> expecting.add(t); } diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaServicesTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaServicesTest.java index 79a92cbeb428..ab171e5a4ecd 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaServicesTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/MetaServicesTest.java @@ -30,11 +30,11 @@ public void loadFileSystemServices() throws Exception { Source.newBuilder( "enso", """ - import Standard.Base.System.File.File_System_SPI - import Standard.Base.Meta - spis = - Meta.lookup_services File_System_SPI - """, + import Standard.Base.System.File.File_System_SPI + import Standard.Base.Meta + spis = + Meta.lookup_services File_System_SPI + """, "services.enso") .uri(uri) .buildLiteral(); @@ -61,11 +61,11 @@ public void missingConversionYieldsDataflowError() { var arr = ctx.evalModule( """ - import Standard.Base.System.File.File_System_SPI - type Broken_Impl + import Standard.Base.System.File.File_System_SPI + type Broken_Impl - main = [File_System_SPI, Broken_Impl] - """); + main = [File_System_SPI, Broken_Impl] + """); var node = new MockLookupServicesNode(); assertTrue("It is an array", arr.hasArrayElements()); assertEquals("Two elements", 2, arr.getArraySize()); @@ -93,14 +93,14 @@ public void conversionThatCreatesNonEnsoObjectYieldsDataflowError() { var arr = ctx.evalModule( """ - import Standard.Base.System.File.File_System_SPI - polyglot java import java.util.Observable - type Broken_Impl + import Standard.Base.System.File.File_System_SPI + polyglot java import java.util.Observable + type Broken_Impl - File_System_SPI.from (_:Broken_Impl) = Observable.new + File_System_SPI.from (_:Broken_Impl) = Observable.new - main = [File_System_SPI, Broken_Impl] - """); + main = [File_System_SPI, Broken_Impl] + """); var node = new MockLookupServicesNode(); assertTrue("It is an array", arr.hasArrayElements()); assertEquals("Two elements", 2, arr.getArraySize()); @@ -128,11 +128,11 @@ public void panicOnSupplierGet() { var arr = ctx.evalModule( """ - import Standard.Base.System.File.File_System_SPI - type Broken_Impl + import Standard.Base.System.File.File_System_SPI + type Broken_Impl - main = [File_System_SPI, Broken_Impl] - """); + main = [File_System_SPI, Broken_Impl] + """); var node = new MockLookupServicesNode(); assertTrue("It is an array", arr.hasArrayElements()); assertEquals("Two elements", 2, arr.getArraySize()); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/TypeMembersTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/TypeMembersTest.java index 081d2ed5741e..7b6dd4f251e0 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/TypeMembersTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/interop/TypeMembersTest.java @@ -33,27 +33,27 @@ public void checkAtomMembers() throws Exception { Source.newBuilder( "enso", """ - from Standard.Base.Data.Boolean import True, False + from Standard.Base.Data.Boolean import True, False - type IntList - End - Head h t + type IntList + End + Head h t - is_empty self = case self of - IntList.End -> True - _ -> False + is_empty self = case self of + IntList.End -> True + _ -> False - tail self = case self of - IntList.Head _ t -> t - _ -> IntList.End + tail self = case self of + IntList.Head _ t -> t + _ -> IntList.End - head self = case self of - IntList.Head h _ -> h - _ -> -1 + head self = case self of + IntList.Head h _ -> h + _ -> -1 - list1 = IntList.Head 7 <| IntList.Head 3 <| IntList.End + list1 = IntList.Head 7 <| IntList.Head 3 <| IntList.End - """, + """, "compare.enso") .uri(uri) .buildLiteral(); @@ -85,14 +85,14 @@ public void ensureNonBuiltinMembersArePresent() throws Exception { Source.newBuilder( "enso", """ - @Builtin_Type - type Compile_Error - Error message + @Builtin_Type + type Compile_Error + Error message - to_display_text self = "Compile error: "+self.message + to_display_text self = "Compile error: "+self.message - v = Compile_Error.Error "foo" - """, + v = Compile_Error.Error "foo" + """, "to_display_text.enso") .uri(uri) .buildLiteral(); @@ -110,9 +110,9 @@ public void builtinMethodIsPresent() { var refType = ctxRule.evalModule( """ - import Standard.Base.Runtime.Ref.Ref - main = Ref - """); + import Standard.Base.Runtime.Ref.Ref + main = Ref + """); assertThat(refType.hasMember("new"), is(true)); } @@ -122,13 +122,13 @@ public void inheritedMembersFromAnyAreIncluded() var type = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type My_Type - method self = 42 + type My_Type + method self = 42 - main = My_Type - """); + main = My_Type + """); var typeUnwrapped = ctxRule.unwrapValue(type); var memberNames = getAllMemberNames(typeUnwrapped); var anyMethods = ctxRule.allMethodsFromAny(); @@ -143,13 +143,13 @@ public void typeMemberNames_AreNotQualified() var type = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type My_Type - method self = 42 + type My_Type + method self = 42 - main = My_Type - """); + main = My_Type + """); var typeUnwrapped = ctxRule.unwrapValue(type); var memberNames = getAllMemberNames(typeUnwrapped); assertThat("Member names are not qualified", memberNames, not(hasItem(containsString(".")))); @@ -160,13 +160,13 @@ public void canInvokeInheritedStaticMethod_OnType() { var myType = ctxRule.evalModule( """ - from Standard.Base.Any import all + from Standard.Base.Any import all - type My_Type - method self = 42 + type My_Type + method self = 42 - main = My_Type - """); + main = My_Type + """); var displayTextRes = myType.invokeMember("to_display_text"); assertThat("Has correct result type", displayTextRes.isString(), is(true)); assertThat("Has correct result value", displayTextRes.asString(), is("My_Type")); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/EnsoProjectTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/EnsoProjectTest.java index 5b5c9caab9e0..e9e801c3c9fc 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/EnsoProjectTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/EnsoProjectTest.java @@ -29,12 +29,12 @@ public void noProjectWhenEvaluatingSingleFile() { var res = ctx.evalModule( """ - from Standard.Base import all - from Standard.Base.Errors.Common import Module_Not_In_Package_Error + from Standard.Base import all + from Standard.Base.Errors.Common import Module_Not_In_Package_Error - main = - enso_project.is_error - """); + main = + enso_project.is_error + """); assertThat(res, notNullValue()); assertThat(res.asBoolean(), is(true)); } @@ -46,10 +46,10 @@ public void ensoProjectWorksInOneProject() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - from Standard.Base import all - main = - enso_project.name - """); + from Standard.Base import all + main = + enso_project.name + """); var projDir = temporaryFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); ProjectUtils.testProjectRun( @@ -65,19 +65,19 @@ public void ensoProjectWorksInTwoProjects() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - from Standard.Base import all + from Standard.Base import all - get_enso_project_name = - enso_project.name - """); + get_enso_project_name = + enso_project.name + """); var mainMod2 = new SourceModule( QualifiedName.fromString("Main"), """ - from local.Proj1 import get_enso_project_name - main = - get_enso_project_name - """); + from local.Proj1 import get_enso_project_name + main = + get_enso_project_name + """); var projDir1 = temporaryFolder.newFolder().toPath(); var projDir2 = temporaryFolder.newFolder().toPath(); ProjectUtils.createProject("Proj1", Set.of(mainMod1), projDir1); @@ -95,10 +95,10 @@ public void ensoProjectCanBeCalledFromJava() throws IOException { new SourceModule( QualifiedName.fromString("Main"), """ - from Standard.Base import all - main = - 42 - """); + from Standard.Base import all + main = + 42 + """); var projDir = temporaryFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mainMod), projDir); var mainModFile = projDir.resolve("src").resolve("Main.enso"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaIsATest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaIsATest.java index 3e65f1b9e3cc..5bd07df74423 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaIsATest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaIsATest.java @@ -55,11 +55,11 @@ public static void prepareCtx() { Source.newBuilder( "enso", """ - from Standard.Base import Meta, Warning + from Standard.Base import Meta, Warning - check x y = Meta.is_a x y - check_warning x = Warning.has_warnings x - """, + check x y = Meta.is_a x y + check_warning x = Warning.has_warnings x + """, "check.enso") .uri(uri) .buildLiteral(); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaTypeMethodsTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaTypeMethodsTest.java index a6a49b8d4e0e..7b9fd2ba67f3 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaTypeMethodsTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/meta/MetaTypeMethodsTest.java @@ -60,11 +60,11 @@ public void testConsistencyBetweenMeta_And_TypeInterop() throws Exception { var interopMembers = interopGetMembers(type); var errMsg = """ - Methods returned from `Meta.get_type_methods` and `InteropLibrary.getMembers` must be the same. - Type: %s - Return value of `Meta.get_type_methods`: %s - Return value of `InteropLibrary.getMembers`: %s - """ + Methods returned from `Meta.get_type_methods` and `InteropLibrary.getMembers` must be the same. + Type: %s + Return value of `Meta.get_type_methods`: %s + Return value of `InteropLibrary.getMembers`: %s + """ .formatted(type, typeMethods, interopMembers); assertThat(errMsg, typeMethods, containsInAnyOrder(interopMembers.toArray(String[]::new))); } @@ -76,12 +76,12 @@ public void inheritedMembersFromNumberAreIncluded() var integerType = ctxRule.evalModule( """ - import Standard.Base.Any.Any - import Standard.Base.Data.Numbers.Number - import Standard.Base.Data.Numbers.Integer + import Standard.Base.Any.Any + import Standard.Base.Data.Numbers.Number + import Standard.Base.Data.Numbers.Integer - main = Integer - """); + main = Integer + """); var anyMethods = methodsFrom("Standard.Base.Any", "Any"); var numberMethods = methodsFrom("Standard.Base.Data.Numbers", "Number"); var integerMethods = methodsFrom("Standard.Base.Data.Numbers", "Integer"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateCheckDisabledTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateCheckDisabledTest.java index 633e8c8cd3f4..d369a4b2ed07 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateCheckDisabledTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateCheckDisabledTest.java @@ -16,7 +16,8 @@ public class PrivateCheckDisabledTest { @Test public void privateCtorCanBeAccessedWhenPrivateCheckIsDisabled() throws IOException { - var libSrc = """ + var libSrc = + """ type T private Cons data """; diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateConstructorAccessTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateConstructorAccessTest.java index af127e439742..47c65846a9ad 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateConstructorAccessTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateConstructorAccessTest.java @@ -45,10 +45,10 @@ public void privateConstructorCanBeCalledInUnknownProject() { public void accessMethodOnATypeWithAllPrivateConstructors() throws IOException { var codeA = """ - type A - private Cons data - find d = A.Cons d - """; + type A + private Cons data + find d = A.Cons d + """; var codeUse = """ import local.Proj_A @@ -69,7 +69,8 @@ public void accessMethodOnATypeWithAllPrivateConstructors() throws IOException { @Test public void privateConstructorIsNotExposedToPolyglot() throws Exception { - var mainSrc = """ + var mainSrc = + """ type My_Type private Cons data """; diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateMethodAccessTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateMethodAccessTest.java index 6c24410ed86b..b6f4bff72098 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateMethodAccessTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/privateaccess/PrivateMethodAccessTest.java @@ -25,9 +25,9 @@ public void moduleDoesNotExposePrivateMethodsToPolyglot() { ctx.eval( LanguageInfo.ID, """ - private priv_method x = x - pub_method x = x - """); + private priv_method x = x + pub_method x = x + """); var assocType = module.invokeMember(Module.GET_ASSOCIATED_TYPE); var privMethod = module.invokeMember(Module.GET_METHOD, assocType, "priv_method"); assertThat("private method must not be exposed to polyglot", privMethod.isNull(), is(true)); @@ -43,10 +43,10 @@ public void typeDoesNotExposePrivateMethodsToPolyglot() { ctx.eval( LanguageInfo.ID, """ - type My_Type - private priv_method x = x - pub_method x = x - """); + type My_Type + private priv_method x = x + pub_method x = x + """); var myType = module.invokeMember(Module.GET_TYPE, "My_Type"); var privMethod = module.invokeMember(Module.GET_METHOD, myType, "priv_method"); assertThat("private method must not be exposed to polyglot", privMethod.isNull(), is(true)); @@ -145,10 +145,12 @@ public void canCallPrivateMethod_ViaLambda() throws IOException { public void canCallPrivateMethod_UnresolvedSymbol() throws IOException { var libDir = tempFolder.newFolder("Lib").toPath(); ProjectUtils.createProject( - "Lib", """ - apply obj func = - func obj - """, libDir); + "Lib", + """ + apply obj func = + func obj + """, + libDir); var projDir = tempFolder.newFolder("Proj").toPath(); ProjectUtils.createProject( diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/scope/ModuleScopeTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/scope/ModuleScopeTest.java index 13c1e70592d1..9deac4b617a1 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/scope/ModuleScopeTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/scope/ModuleScopeTest.java @@ -29,10 +29,10 @@ public void extensionMethodIsRegisteredInModuleScope() throws IOException { Source.newBuilder( LanguageInfo.ID, """ - type My_Type - Value x - My_Type.extension_method self = self.x - """, + type My_Type + Value x + My_Type.extension_method self = self.x + """, "test.enso") .build(); var mainMod = ctxRule.eval(mainSrc); @@ -49,17 +49,17 @@ public void staticMethodIsInResolvedExports() throws IOException { new SourceModule( QualifiedName.fromString("A_module"), """ - type My_Type - My_Type.extension_method self = 42 - """); + type My_Type + My_Type.extension_method self = 42 + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - export project.A_Module.My_Type - export project.A_Module.extension_method - main = 42 - """); + export project.A_Module.My_Type + export project.A_Module.extension_method + main = 42 + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(aMod, mainMod), projDir); } @@ -70,9 +70,9 @@ public void staticMethodIsRegisteredInModuleScope() throws IOException { Source.newBuilder( LanguageInfo.ID, """ - type My_Type - static_method _ = 42 - """, + type My_Type + static_method _ = 42 + """, "test.enso") .build(); var mainMod = ctxRule.eval(mainSrc); @@ -87,9 +87,11 @@ public void staticMethodIsRegisteredInModuleScope() throws IOException { public void moduleMethodIsRegisteredInModuleScope() throws IOException { var mainSrc = Source.newBuilder( - LanguageInfo.ID, """ - module_method _ = 42 - """, "test.enso") + LanguageInfo.ID, + """ + module_method _ = 42 + """, + "test.enso") .build(); // ModuleScope is populated in IrToTruffle - at runtime. So we have to evaluate // the main module before we inspect the ModuleScope. @@ -107,16 +109,16 @@ public void importedStaticMethodIsRegisteredInModuleScope() throws IOException { new SourceModule( QualifiedName.fromString("Mod"), """ - type My_Type - static_method _ = 1 - """); + type My_Type + static_method _ = 1 + """); var mainMod = new SourceModule( QualifiedName.fromString("Main"), """ - from project.Mod import My_Type - main = 2 - """); + from project.Mod import My_Type + main = 2 + """); var projDir = tempFolder.newFolder().toPath(); ProjectUtils.createProject("Proj", Set.of(mod, mainMod), projDir); var mainSrcPath = projDir.resolve("src").resolve("Main.enso"); diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/DataflowErrorPropagationTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/DataflowErrorPropagationTest.java index ba26c79b8a09..d1d6cfca4186 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/DataflowErrorPropagationTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/DataflowErrorPropagationTest.java @@ -24,20 +24,20 @@ public static void prepareCtx() { var ctx = ctxRule.context(); var code = """ - from Standard.Base import all + from Standard.Base import all - private yield_error yes:Boolean -> Text = - if yes then Error.throw "Yielding an error" else - "OK" + private yield_error yes:Boolean -> Text = + if yes then Error.throw "Yielding an error" else + "OK" - suppress_error yes:Boolean value = - yield_error yes - value + suppress_error yes:Boolean value = + yield_error yes + value - suppress_error_with_assign yes:Boolean value = - _ = yield_error yes - value - """; + suppress_error_with_assign yes:Boolean value = + _ = yield_error yes + value + """; suppressError = ctx.eval("enso", code).invokeMember(MethodNames.Module.EVAL_EXPRESSION, "suppress_error"); suppressErrorWithAssign = diff --git a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/FunctionIdentityTest.java b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/FunctionIdentityTest.java index d03bc4e7c733..cce0731667f8 100644 --- a/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/FunctionIdentityTest.java +++ b/engine/runtime-integration-tests/src/test/java/org/enso/interpreter/test/semantic/FunctionIdentityTest.java @@ -17,7 +17,8 @@ public class FunctionIdentityTest { @Test public void functionWithArgIdentity() throws Exception { - var rawCode = """ + var rawCode = + """ am_i_me _ = am_i_me... """; assertFunctionIdentity(rawCode, "Am_I_Me_With_Arg"); @@ -25,7 +26,8 @@ public void functionWithArgIdentity() throws Exception { @Test public void functionIdentity() throws Exception { - var rawCode = """ + var rawCode = + """ am_i_me = am_i_me... """; assertFunctionIdentity(rawCode, "Am_I_Me"); diff --git a/engine/runtime-language-arrow/src/main/java/org/enso/interpreter/arrow/node/ArrowEvalNode.java b/engine/runtime-language-arrow/src/main/java/org/enso/interpreter/arrow/node/ArrowEvalNode.java index 7619cb2fc396..f3bab2966dde 100644 --- a/engine/runtime-language-arrow/src/main/java/org/enso/interpreter/arrow/node/ArrowEvalNode.java +++ b/engine/runtime-language-arrow/src/main/java/org/enso/interpreter/arrow/node/ArrowEvalNode.java @@ -24,12 +24,13 @@ private ArrowEvalNode(ArrowLanguage language, ArrowParser.Result code) { public Object execute(VirtualFrame frame) { return switch (code.physicalLayout()) { - case Primitive -> switch (code.mode()) { - case Allocate -> new ArrowFixedSizeArrayFactory(code.logicalLayout()); - case Cast -> new ArrowCastToFixedSizeArrayFactory(code.logicalLayout()); - case Plus -> new ArrowOperationPlus(code.logicalLayout()); - default -> throw CompilerDirectives.shouldNotReachHere("unsupported mode"); - }; + case Primitive -> + switch (code.mode()) { + case Allocate -> new ArrowFixedSizeArrayFactory(code.logicalLayout()); + case Cast -> new ArrowCastToFixedSizeArrayFactory(code.logicalLayout()); + case Plus -> new ArrowOperationPlus(code.logicalLayout()); + default -> throw CompilerDirectives.shouldNotReachHere("unsupported mode"); + }; default -> throw CompilerDirectives.shouldNotReachHere("unsupported physical layout"); }; } diff --git a/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/ForeignEvalNode.java b/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/ForeignEvalNode.java index b2defad906a0..8a6e91423b5b 100644 --- a/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/ForeignEvalNode.java +++ b/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/ForeignEvalNode.java @@ -83,14 +83,15 @@ public Object execute(VirtualFrame frame) { var installedLanguages = context.getEnv().getPublicLanguages(); var node = switch (installedLanguages.containsKey(id) ? 1 : 0) { - case 0 -> switch (id) { - case "java" -> parseJava(); - default -> { - var sortedLangs = new TreeSet<>(installedLanguages.keySet()); - var ex = new ForeignParsingException(id, sortedLangs, this); - yield new ExceptionForeignNode(ex); - } - }; + case 0 -> + switch (id) { + case "java" -> parseJava(); + default -> { + var sortedLangs = new TreeSet<>(installedLanguages.keySet()); + var ex = new ForeignParsingException(id, sortedLangs, this); + yield new ExceptionForeignNode(ex); + } + }; default -> { context.log( Level.FINE, diff --git a/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/PyForeignNode.java b/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/PyForeignNode.java index 697bbb3d9be7..6787b239bfdb 100644 --- a/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/PyForeignNode.java +++ b/engine/runtime-language-epb/src/main/java/org/enso/interpreter/epb/PyForeignNode.java @@ -83,11 +83,11 @@ private Object none() Source.newBuilder( "python", """ - import site - def nothing(): - return None - nothing - """, + import site + def nothing(): + return None + nothing + """, "nothing.py") .build(); var nothingFn = ctx.getEnv().parsePublic(src).call(); @@ -107,9 +107,9 @@ private Object wrapPythonDate(LocalDate date) Source.newBuilder( "python", """ - from datetime import date - date - """, + from datetime import date + date + """, "convert_date.py") .build(); @@ -129,9 +129,9 @@ private Object wrapPythonTime(LocalTime time) Source.newBuilder( "python", """ - from datetime import time - time - """, + from datetime import time + time + """, "convert_time.py") .build(); fnPythonTime = ctx.getEnv().parsePublic(src).call(); @@ -150,28 +150,28 @@ private Object wrapPythonZone(ZoneId zone, LocalTime time, LocalDate date) Source.newBuilder( "python", """ - from datetime import timezone, timedelta, tzinfo + from datetime import timezone, timedelta, tzinfo - class EnsoTzInfo(tzinfo): - def __init__(self, rules): - self._rules = rules + class EnsoTzInfo(tzinfo): + def __init__(self, rules): + self._rules = rules - def utcoffset(self, when): - when = when.replace(tzinfo=None) - d = timedelta(seconds=self._rules.offset(when)) - return d + def utcoffset(self, when): + when = when.replace(tzinfo=None) + d = timedelta(seconds=self._rules.offset(when)) + return d - def tzname(self, dt): - return self._rules.name(dt) + def tzname(self, dt): + return self._rules.name(dt) - def dst(self, dt): - return self._rules.dst(dt); + def dst(self, dt): + return self._rules.dst(dt); - def conv(rules): - return EnsoTzInfo(rules) + def conv(rules): + return EnsoTzInfo(rules) - conv - """, + conv + """, "convert_time_zone.py") .build(); @@ -190,9 +190,9 @@ private Object combinePythonDateTimeZone(Object date, Object time, Object zone) Source.newBuilder( "python", """ - from datetime import datetime - datetime.combine - """, + from datetime import datetime + datetime.combine + """, "convert_combine.py") .build(); diff --git a/engine/runtime-language-epb/src/test/java/org/enso/interpreter/epb/ForeignEvalNodeTest.java b/engine/runtime-language-epb/src/test/java/org/enso/interpreter/epb/ForeignEvalNodeTest.java index 28f0d1ec7d00..6d1aa35f4e0b 100644 --- a/engine/runtime-language-epb/src/test/java/org/enso/interpreter/epb/ForeignEvalNodeTest.java +++ b/engine/runtime-language-epb/src/test/java/org/enso/interpreter/epb/ForeignEvalNodeTest.java @@ -13,9 +13,14 @@ public ForeignEvalNodeTest() {} @Test public void sourceWithoutHash() throws Exception { - var src = Source.newBuilder("epb", """ - nonsensecontent - """, "simple.test").build(); + var src = + Source.newBuilder( + "epb", + """ + nonsensecontent + """, + "simple.test") + .build(); var node = ForeignEvalNode.parse(null, src, Collections.emptyList()); try { diff --git a/engine/runtime-parser-processor-tests/src/test/java/org/enso/runtime/parser/processor/test/TestIRProcessorInline.java b/engine/runtime-parser-processor-tests/src/test/java/org/enso/runtime/parser/processor/test/TestIRProcessorInline.java index 4fe757e9c2c7..2781cea7fd4c 100644 --- a/engine/runtime-parser-processor-tests/src/test/java/org/enso/runtime/parser/processor/test/TestIRProcessorInline.java +++ b/engine/runtime-parser-processor-tests/src/test/java/org/enso/runtime/parser/processor/test/TestIRProcessorInline.java @@ -73,20 +73,20 @@ public void simpleIRNodeWithoutFields_CompilationSucceeds() { JavaFileObjects.forSourceString( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName() {} + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName() {} - @Override - public String showCode(int indent) { - return ""; - } - } - """); + @Override + public String showCode(int indent) { + return ""; + } + } + """); var compiler = Compiler.javac().withProcessors(new IRProcessor()); var compilation = compiler.compile(src); CompilationSubject.assertThat(compilation).succeeded(); @@ -98,14 +98,14 @@ public void onlyFinalClassCanBeAnnotated() { JavaFileObjects.forSourceString( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - @GenerateIR - public class JName extends JNameGen { - @GenerateFields - public JName() {} - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + @GenerateIR + public class JName extends JNameGen { + @GenerateFields + public JName() {} + } + """); var compiler = Compiler.javac().withProcessors(new IRProcessor()); var compilation = compiler.compile(src); CompilationSubject.assertThat(compilation).failed(); @@ -118,10 +118,10 @@ public void annotatedClass_MustHaveAnnotatedConstructor() { JavaFileObjects.forSourceString( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - @GenerateIR - public final class JName {} - """); + import org.enso.runtime.parser.dsl.GenerateIR; + @GenerateIR + public final class JName {} + """); var compiler = Compiler.javac().withProcessors(new IRProcessor()); var compilation = compiler.compile(src); CompilationSubject.assertThat(compilation).failed(); @@ -156,23 +156,23 @@ public String showCode(int indent) { public void annotatedClass_InterfacesToImplement_CanHaveMore() { var src = """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.compiler.core.IR; - - interface MySuperIR { } - - @GenerateIR(interfaces = {MySuperIR.class, IR.class}) - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR() {} - - @Override - public String showCode(int indent) { - return ""; - } - } - """; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.compiler.core.IR; + + interface MySuperIR { } + + @GenerateIR(interfaces = {MySuperIR.class, IR.class}) + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR() {} + + @Override + public String showCode(int indent) { + return ""; + } + } + """; var generatedClass = generatedClass("MyIR", src); assertThat(generatedClass, containsString("class MyIRGen implements IR, MySuperIR")); } @@ -180,7 +180,7 @@ public String showCode(int indent) { @Test public void annotatedClass_InterfacesToImplement_DoNotHaveToExtendIR() { var src = - """ +""" import org.enso.runtime.parser.dsl.GenerateIR; import org.enso.runtime.parser.dsl.GenerateFields; @@ -551,24 +551,24 @@ public void simpleIRNodeWithChild() { generatedClass( "MyIR", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.ir.Expression; - - @GenerateIR - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR(@IRChild Expression expression) { - super(expression); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.ir.Expression; + + @GenerateIR + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR(@IRChild Expression expression) { + super(expression); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(genSrc, containsString("Expression expression()")); } @@ -578,24 +578,24 @@ public void irNodeWithMultipleFields_PrimitiveField() { generatedClass( "MyIR", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.runtime.parser.dsl.IRField; - - @GenerateIR - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR(@IRField boolean suspended) { - super(suspended); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.runtime.parser.dsl.IRField; + + @GenerateIR + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR(@IRField boolean suspended) { + super(suspended); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(genSrc, containsString("boolean suspended()")); } @@ -605,28 +605,28 @@ public void irNodeWithInheritedField() { generatedClass( "MyIR", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRField; - import org.enso.compiler.core.IR; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRField; + import org.enso.compiler.core.IR; - interface MySuperIR extends IR { - boolean suspended(); - } + interface MySuperIR extends IR { + boolean suspended(); + } - @GenerateIR(interfaces = {MySuperIR.class}) - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR(@IRField boolean suspended) { - super(suspended); - } + @GenerateIR(interfaces = {MySuperIR.class}) + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR(@IRField boolean suspended) { + super(suspended); + } - @Override - public String showCode(int indent) { - return ""; - } - } - """); + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("boolean suspended()")); } @@ -636,29 +636,29 @@ public void irNodeWithInheritedField_Override() { generatedClass( "MyIR", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRField; - import org.enso.compiler.core.IR; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRField; + import org.enso.compiler.core.IR; - interface MySuperIR extends IR { - boolean suspended(); - } + interface MySuperIR extends IR { + boolean suspended(); + } - @GenerateIR - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR(@IRField boolean suspended) { - super(suspended); - } + @GenerateIR + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR(@IRField boolean suspended) { + super(suspended); + } - @Override - public String showCode(int indent) { - return ""; - } - } + @Override + public String showCode(int indent) { + return ""; + } + } - """); + """); assertThat(src, containsString("boolean suspended()")); } @@ -668,31 +668,31 @@ public void irNodeWithInheritedField_Transitive() { generatedClass( "MyIR", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRField; - import org.enso.compiler.core.IR; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRField; + import org.enso.compiler.core.IR; - interface MySuperSuperIR extends IR { - boolean suspended(); - } + interface MySuperSuperIR extends IR { + boolean suspended(); + } - interface MySuperIR extends MySuperSuperIR { - } + interface MySuperIR extends MySuperSuperIR { + } - @GenerateIR(interfaces = {MySuperIR.class}) - public final class MyIR extends MyIRGen { - @GenerateFields - public MyIR(@IRField boolean suspended) { - super(suspended); - } + @GenerateIR(interfaces = {MySuperIR.class}) + public final class MyIR extends MyIRGen { + @GenerateFields + public MyIR(@IRField boolean suspended) { + super(suspended); + } - @Override - public String showCode(int indent) { - return ""; - } - } - """); + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("boolean suspended()")); } @@ -702,28 +702,28 @@ public void irNodeAsNestedClass() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRField; - import org.enso.compiler.core.IR; - - public interface JName extends IR { - String name(); - - @GenerateIR(interfaces = {JName.class}) - public final class JBlank extends JBlankGen { - @GenerateFields - public JBlank(@IRField String name) { - super(name); - } - - @Override - public String showCode(int indent) { - return ""; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRField; + import org.enso.compiler.core.IR; + + public interface JName extends IR { + String name(); + + @GenerateIR(interfaces = {JName.class}) + public final class JBlank extends JBlankGen { + @GenerateFields + public JBlank(@IRField String name) { + super(name); + } + + @Override + public String showCode(int indent) { + return ""; + } + } } - } - } - """); + """); assertThat(src, containsString("class JBlankGen implements IR, JName")); assertThat(src, containsString("String name()")); } @@ -734,25 +734,25 @@ public void fieldCanBeScalaList() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.IR; - import scala.collection.immutable.List; - - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName(@IRChild List expressions) { - super(expressions); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.IR; + import scala.collection.immutable.List; + + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName(@IRChild List expressions) { + super(expressions); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("class JNameGen")); assertThat(src, containsString("List expressions")); } @@ -763,25 +763,25 @@ public void fieldCanBeScalaList_NotRequired() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.IR; - import scala.collection.immutable.List; - - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName(@IRChild(required = false) List expressions) { - super(expressions); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.IR; + import scala.collection.immutable.List; + + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName(@IRChild(required = false) List expressions) { + super(expressions); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("class JNameGen")); assertThat(src, containsString("List expressions")); // expressions child is not required, so there must be somewhere a check @@ -795,26 +795,26 @@ public void fieldCanBeScalaOptionList() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.IR; - import scala.collection.immutable.List; - import scala.Option; - - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName(@IRChild Option> expressions) { - super(expressions); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.IR; + import scala.collection.immutable.List; + import scala.Option; + + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName(@IRChild Option> expressions) { + super(expressions); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("class JNameGen")); assertThat(src, containsString("Option> expressions")); assertThat(src, containsString("expressions.isDefined")); @@ -826,25 +826,25 @@ public void fieldCanBeScalaOption() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.IR; - import scala.Option; - - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName(@IRChild Option expression) { - super(expression); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.IR; + import scala.Option; + + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName(@IRChild Option expression) { + super(expression); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("class JNameGen")); assertThat("has getter method for expression", src, containsString("Option expression()")); } @@ -855,25 +855,25 @@ public void fieldCanBePersistanceReference() { generatedClass( "JName", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.persist.Persistance; - import org.enso.compiler.core.IR; - - @GenerateIR - public final class JName extends JNameGen { - @GenerateFields - public JName(@IRChild Persistance.Reference expression) { - super(expression); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - """); + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.persist.Persistance; + import org.enso.compiler.core.IR; + + @GenerateIR + public final class JName extends JNameGen { + @GenerateFields + public JName(@IRChild Persistance.Reference expression) { + super(expression); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + """); assertThat(src, containsString("class JNameGen")); assertThat( "has getter method for expression with the same return type", @@ -888,40 +888,40 @@ public void canReferenceSiblingInterfaceInIRChild() { expectCompilationSuccessful( "JCase", """ - import org.enso.runtime.parser.dsl.GenerateIR; - import org.enso.runtime.parser.dsl.GenerateFields; - import org.enso.runtime.parser.dsl.IRChild; - import org.enso.compiler.core.IR; - - public interface JCase extends IR { - - @GenerateIR(interfaces = {JCase.class}) - final class JExpr extends JExprGen { - @GenerateFields - public JExpr(@IRChild JBranch branch) { - super(branch); - } - - @Override - public String showCode(int indent) { - return ""; - } - } - - @GenerateIR(interfaces = {JCase.class}) - final class JBranch extends JBranchGen { - @GenerateFields - public JBranch() { - super(); - } - - @Override - public String showCode(int indent) { - return ""; + import org.enso.runtime.parser.dsl.GenerateIR; + import org.enso.runtime.parser.dsl.GenerateFields; + import org.enso.runtime.parser.dsl.IRChild; + import org.enso.compiler.core.IR; + + public interface JCase extends IR { + + @GenerateIR(interfaces = {JCase.class}) + final class JExpr extends JExprGen { + @GenerateFields + public JExpr(@IRChild JBranch branch) { + super(branch); + } + + @Override + public String showCode(int indent) { + return ""; + } + } + + @GenerateIR(interfaces = {JCase.class}) + final class JBranch extends JBranchGen { + @GenerateFields + public JBranch() { + super(); + } + + @Override + public String showCode(int indent) { + return ""; + } + } } - } - } - """); + """); var generatedSrcs = compilation.generatedSourceFiles(); assertThat(generatedSrcs.size(), is(2)); } diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/IRNodeClassGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/IRNodeClassGenerator.java index 10d1be68e810..887a247f6445 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/IRNodeClassGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/IRNodeClassGenerator.java @@ -226,9 +226,9 @@ private String fieldsCode() { .map( field -> """ - ${comment} - private final ${type} ${name}; - """ + ${comment} + private final ${type} ${name}; + """ .replace("${comment}", commentForField(field)) .replace("${type}", field.getSimpleTypeName()) .replace("${name}", field.getName())) @@ -275,12 +275,12 @@ private String commentForField(Field field) { var isChild = "" + field.isChild(); var isNullable = "" + field.isNullable(); return """ - /** - * Created from ${matchingCtorInfo}. - *

- isNullable: ${isNullable}. - *

- isChild: ${isChild}. - */ - """ + /** + * Created from ${matchingCtorInfo}. + *

- isNullable: ${isNullable}. + *

- isChild: ${isChild}. + */ + """ .replace("${isChild}", isChild) .replace("${isNullable}", isNullable) .replace("${matchingCtorInfo}", matchingCtorInfo) @@ -382,10 +382,10 @@ private String validateConstructor() { .map( notNullField -> """ - if ($fieldName == null) { - throw new IllegalArgumentException("$fieldName is required"); - } - """ + if ($fieldName == null) { + throw new IllegalArgumentException("$fieldName is required"); + } + """ .replace("$fieldName", notNullField.name())) .collect(Collectors.joining(System.lineSeparator())); sb.append(Utils.indent(checkCode, 2)); diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/BuilderMethodGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/BuilderMethodGenerator.java index cee8f385f17c..b5e0f815cd64 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/BuilderMethodGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/BuilderMethodGenerator.java @@ -37,11 +37,11 @@ public String generateBuilder() { .map( field -> """ - public Builder $fieldName($fieldType $fieldName) { - this.$fieldName = $fieldName; - return this; - } - """ + public Builder $fieldName($fieldType $fieldName) { + this.$fieldName = $fieldName; + return this; + } + """ .replace("$fieldName", field.name()) .replace("$fieldType", field.getSimpleTypeName())) .collect(Collectors.joining(System.lineSeparator())); @@ -53,10 +53,10 @@ public String generateBuilder() { .map( field -> """ - if (this.$fieldName == null) { - throw new IllegalArgumentException("$fieldName is required"); - } - """ + if (this.$fieldName == null) { + throw new IllegalArgumentException("$fieldName is required"); + } + """ .replace("$fieldName", field.getName())) .collect(Collectors.joining(System.lineSeparator())); diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ChildrenMethodGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ChildrenMethodGenerator.java index dd2d1f490df0..08e6b60d9fbb 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ChildrenMethodGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ChildrenMethodGenerator.java @@ -31,8 +31,8 @@ public String generateCode() { case ListField listField -> addListCode(listField); case OptionField optionField -> addOptionCode(optionField); case OptionListField optionListField -> addOptionListCode(optionListField); - case PersistanceReferenceField - persistanceReferenceField -> addPersistanceRefCode(persistanceReferenceField); + case PersistanceReferenceField persistanceReferenceField -> + addPersistanceRefCode(persistanceReferenceField); default -> addFieldCode(userField); }; sb.append(Utils.indent(addToListCode)); @@ -99,10 +99,10 @@ private String addFieldCode(Field field) { Utils.hardAssert(!(field instanceof PersistanceReferenceField)); if (field.isNullable()) { return """ - if (${fieldName} != null) { - list.add(${fieldName}); - } - """ + if (${fieldName} != null) { + list.add(${fieldName}); + } + """ .replace("${fieldName}", field.getName()); } else { return "list.add(" + field.getName() + ");"; diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/DuplicateMethodGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/DuplicateMethodGenerator.java index ca0cfd70d915..78c35a6d78fd 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/DuplicateMethodGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/DuplicateMethodGenerator.java @@ -192,14 +192,14 @@ private static String dupFieldName(Field field) { private String nullableChildCode(Field nullableChild) { Utils.hardAssert(nullableChild.isNullable() && nullableChild.isChild()); return """ - IR $dupName = null; - if ($childName != null) { - $dupName = $childName.duplicate($parameterNames); - if (!($dupName instanceof $childType)) { - throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); - } - } - """ + IR $dupName = null; + if ($childName != null) { + $dupName = $childName.duplicate($parameterNames); + if (!($dupName instanceof $childType)) { + throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); + } + } + """ .replace("$childType", nullableChild.getSimpleTypeName()) .replace("$childName", nullableChild.getName()) .replace("$dupName", dupFieldName(nullableChild)) @@ -209,11 +209,11 @@ private String nullableChildCode(Field nullableChild) { private String notNullableChildCode(Field child) { assert child.isChild() && !child.isNullable() && !child.isList() && !child.isOption(); return """ - IR $dupName = $childName.duplicate($parameterNames); - if (!($dupName instanceof $childType)) { - throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); - } - """ + IR $dupName = $childName.duplicate($parameterNames); + if (!($dupName instanceof $childType)) { + throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); + } + """ .replace("$childType", child.getSimpleTypeName()) .replace("$childName", child.getName()) .replace("$dupName", dupFieldName(child)) @@ -223,17 +223,17 @@ private String notNullableChildCode(Field child) { private String listChildCode(Field listChild) { Utils.hardAssert(listChild.isChild() && listChild.isList()); return """ - $childListType $dupName = null; - if ($childName != null) { - $dupName = $childName.map(child -> { - IR dupChild = child.duplicate($parameterNames); - if (!(dupChild instanceof $childType)) { - throw new IllegalStateException("Duplicated child is not of the expected type: " + dupChild); - } - return ($childType) dupChild; - }); - } - """ + $childListType $dupName = null; + if ($childName != null) { + $dupName = $childName.map(child -> { + IR dupChild = child.duplicate($parameterNames); + if (!(dupChild instanceof $childType)) { + throw new IllegalStateException("Duplicated child is not of the expected type: " + dupChild); + } + return ($childType) dupChild; + }); + } + """ .replace("$childListType", listChild.getSimpleTypeName()) .replace("$childType", listChild.getTypeParameter().getSimpleName()) .replace("$childName", listChild.getName()) @@ -244,15 +244,15 @@ private String listChildCode(Field listChild) { private String optionChildCode(Field optionChild) { Utils.hardAssert(optionChild.isOption() && optionChild.isChild()); return """ - $childOptType $dupName = $childName; - if ($childName.isDefined()) { - var duplicated = $childName.get().duplicate($parameterNames); - if (!(duplicated instanceof $childType)) { - throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); - } - $dupName = Option.apply(duplicated); - } - """ + $childOptType $dupName = $childName; + if ($childName.isDefined()) { + var duplicated = $childName.get().duplicate($parameterNames); + if (!(duplicated instanceof $childType)) { + throw new IllegalStateException("Duplicated child is not of the expected type: " + $dupName); + } + $dupName = Option.apply(duplicated); + } + """ .replace("$childOptType", optionChild.getSimpleTypeName()) .replace("$childType", optionChild.getTypeParameter().getSimpleName()) .replace("$childName", optionChild.getName()) @@ -262,17 +262,17 @@ private String optionChildCode(Field optionChild) { private String optionListChildCode(OptionListField optionListChild) { return """ - var ${dupName} = ${childName}; - if (${childName}.isDefined()) { - ${childName}.get().map(child -> { - IR dupChild = child.duplicate(${parameterNames}); - if (!(dupChild instanceof ${childType})) { - throw new IllegalStateException("Duplicated child is not of the expected type: " + dupChild); - } - return (${childType}) dupChild; - }); + var ${dupName} = ${childName}; + if (${childName}.isDefined()) { + ${childName}.get().map(child -> { + IR dupChild = child.duplicate(${parameterNames}); + if (!(dupChild instanceof ${childType})) { + throw new IllegalStateException("Duplicated child is not of the expected type: " + dupChild); } - """ + return (${childType}) dupChild; + }); + } + """ .replace("${childName}", optionListChild.getName()) .replace("${childType}", optionListChild.getNestedTypeParameter().getSimpleName()) .replace("${dupName}", dupFieldName(optionListChild)) @@ -282,14 +282,14 @@ private String optionListChildCode(OptionListField optionListChild) { private String persistanceReferenceCode(Field perRefChild) { Utils.hardAssert(perRefChild.isPersistanceReference()); return """ - ${perRefType} ${dupName}; - { - ${type} duplicated = ${childName} - .get(${type}.class) - .duplicate(${parameterNames}); - ${dupName} = Reference.of(duplicated); - } - """ + ${perRefType} ${dupName}; + { + ${type} duplicated = ${childName} + .get(${type}.class) + .duplicate(${parameterNames}); + ${dupName} = Reference.of(duplicated); + } + """ .replace("${perRefType}", perRefChild.getSimpleTypeName()) .replace("${type}", perRefChild.getTypeParameter().getSimpleName()) .replace("${childName}", perRefChild.getName()) @@ -300,8 +300,8 @@ private String persistanceReferenceCode(Field perRefChild) { private static String nonChildCode(Field field) { Utils.hardAssert(!field.isChild()); return """ - $childType $dupName = $childName; - """ + $childType $dupName = $childName; + """ .replace("$childType", field.getSimpleTypeName()) .replace("$childName", field.getName()) .replace("$dupName", dupFieldName(field)); diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/MapExpressionsMethodGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/MapExpressionsMethodGenerator.java index 6705d94abdd9..45b574037f20 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/MapExpressionsMethodGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/MapExpressionsMethodGenerator.java @@ -104,12 +104,12 @@ public String generateMapExpressionsMethodCode() { var newChildName = child.getName() + "Mapped"; var mapCode = switch (child) { - case PersistanceReferenceField perRefField -> mapPersistanceReference( - newChildName, perRefField); + case PersistanceReferenceField perRefField -> + mapPersistanceReference(newChildName, perRefField); case ListField listField -> mapList(newChildName, listField); case OptionField optionField -> mapOption(newChildName, optionField); - case OptionListField optionListField -> mapOptionListField( - newChildName, optionListField); + case OptionListField optionListField -> + mapOptionListField(newChildName, optionListField); default -> mapOther(newChildName, newChildType, child); }; var startComment = @@ -231,42 +231,42 @@ private String doMapExprCode() { if (isProcessingDefinitionArgument()) { specialHandling.append( """ - // Special case - name of DefinitionArgument is not applied. - // This means no `fn.apply` call on it. - assert this instanceof ${defArgClass}; - if (ir == this.name()) { - return (T) ir.mapExpressions(fn); - } - """ + // Special case - name of DefinitionArgument is not applied. + // This means no `fn.apply` call on it. + assert this instanceof ${defArgClass}; + if (ir == this.name()) { + return (T) ir.mapExpressions(fn); + } + """ .replace("${defArgClass}", DEF_ARG_CLASS)); } if (isProcessingCallArgument()) { specialHandling.append( """ - // Special case - name of CallArgument is not applied. - // This means no `fn.apply` call on it. - assert this instanceof ${callArgClass}; - if (this.name().isDefined() - && ir == this.name().get()) { - return (T) ir.mapExpressions(fn); - } - """ + // Special case - name of CallArgument is not applied. + // This means no `fn.apply` call on it. + assert this instanceof ${callArgClass}; + if (this.name().isDefined() + && ir == this.name().get()) { + return (T) ir.mapExpressions(fn); + } + """ .replace("${callArgClass}", CALL_ARG_CLASS)); } var code = """ - @SuppressWarnings("unchecked") - private T doMapExpr( - T ir, - java.util.function.Function fn) { - ${specialHandling} - // Either recurse to `mapExpression` or call `fn.apply` on the expression. - return switch(ir) { - case Expression expr -> (T) fn.apply(expr); - default -> (T) ir.mapExpressions(fn); - }; - } - """ + @SuppressWarnings("unchecked") + private T doMapExpr( + T ir, + java.util.function.Function fn) { + ${specialHandling} + // Either recurse to `mapExpression` or call `fn.apply` on the expression. + return switch(ir) { + case Expression expr -> (T) fn.apply(expr); + default -> (T) ir.mapExpressions(fn); + }; + } + """ .replace("${specialHandling}", specialHandling.toString()); return code; } diff --git a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ToStringMethodGenerator.java b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ToStringMethodGenerator.java index b9281b84beb0..c3a90e2cd765 100644 --- a/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ToStringMethodGenerator.java +++ b/engine/runtime-parser-processor/src/main/java/org/enso/runtime/parser/processor/methodgen/ToStringMethodGenerator.java @@ -42,12 +42,12 @@ public String generateMethodCode() { private String toSingleLineMethod() { return """ - private static String toSingleLine(String str) { - return str.trim().lines() - .map(s -> s.trim()) - .collect(Collectors.joining(" ")); - } - """; + private static String toSingleLine(String str) { + return str.trim().lines() + .map(s -> s.trim()) + .collect(Collectors.joining(" ")); + } + """; } private String className() { diff --git a/engine/runtime-parser/src/main/java/org/enso/compiler/core/TreeToIr.java b/engine/runtime-parser/src/main/java/org/enso/compiler/core/TreeToIr.java index c06aa1ebe3b1..9fe9da5af96f 100644 --- a/engine/runtime-parser/src/main/java/org/enso/compiler/core/TreeToIr.java +++ b/engine/runtime-parser/src/main/java/org/enso/compiler/core/TreeToIr.java @@ -5,7 +5,6 @@ import java.util.Collections; import java.util.Map; import java.util.UUID; - import org.enso.compiler.core.ir.AscriptionReason; import org.enso.compiler.core.ir.CallArgument; import org.enso.compiler.core.ir.DefinitionArgument; @@ -49,7 +48,6 @@ import org.enso.syntax2.Tree; import org.enso.syntax2.TypeSignature; import org.enso.syntax2.TypeSignatureLine; - import scala.Option; import scala.collection.immutable.LinearSeq; import scala.collection.immutable.List; @@ -88,13 +86,13 @@ Expression.Block translateBlock(Tree.BodyBlock ast) { /** * Translates an inline program expression represented in the parser {@link Tree} to the * compiler's {@link IR} representation. - *

- * Inline expressions must only be expressions, and may not contain any type of + * + *

Inline expressions must only be expressions, and may not contain any type of * definition. * * @param ast The tree representing the expression to translate. - * @return The {@link IR} representation of the given ast if it is valid, otherwise - * {@link Option#empty()}. + * @return The {@link IR} representation of the given ast if it is valid, otherwise {@link + * Option#empty()}. */ Option translateInline(Tree.BodyBlock ast) { var expressions = new ArrayList(); @@ -108,7 +106,7 @@ Option translateInline(Tree.BodyBlock ast) { case Tree.TypeSignatureDeclaration sigDeclaration -> { Expression sigIr; try { - sigIr = (Expression)translateMethodTypeSignature(sigDeclaration.getSignature()); + sigIr = (Expression) translateMethodTypeSignature(sigDeclaration.getSignature()); } catch (SyntaxException ex) { sigIr = ex.toError(); } @@ -139,23 +137,20 @@ Option translateInline(Tree.BodyBlock ast) { IdentifiedLocation combinedLocation = null; if (firstLocation != null && lastLocation != null) { combinedLocation = - new IdentifiedLocation( - new Location(firstLocation.start(), lastLocation.end()), - null - ); + new IdentifiedLocation(new Location(firstLocation.start(), lastLocation.end()), null); } Expression returnValue = null; if (!expressions.isEmpty()) { returnValue = expressions.get(expressions.size() - 1); expressions.remove(expressions.size() - 1); } - yield Option.apply(new Expression.Block( - CollectionConverters.asScala(expressions.iterator()).toList(), - returnValue, - combinedLocation, - false, - meta() - )); + yield Option.apply( + new Expression.Block( + CollectionConverters.asScala(expressions.iterator()).toList(), + returnValue, + combinedLocation, + false, + meta())); } }; } @@ -193,17 +188,27 @@ Module translateModule(Tree.BodyBlock module) { } isPrivate = true; } - case null -> { - } + case null -> {} default -> bindings = translateModuleSymbol(expr, bindings); } } if (!diag.isEmpty()) { - return new Module(imports.reverse(), exports.reverse(), bindings.reverse(), isPrivate, - getIdentifiedLocation(module), meta(), new DiagnosticStorage(diag)); + return new Module( + imports.reverse(), + exports.reverse(), + bindings.reverse(), + isPrivate, + getIdentifiedLocation(module), + meta(), + new DiagnosticStorage(diag)); } else { - return new Module(imports.reverse(), exports.reverse(), bindings.reverse(), isPrivate, - getIdentifiedLocation(module), meta()); + return new Module( + imports.reverse(), + exports.reverse(), + bindings.reverse(), + isPrivate, + getIdentifiedLocation(module), + meta()); } } @@ -234,13 +239,9 @@ private List translateModuleSymbolImpl(Tree inputAst, List args = translateArgumentsDefinition(def.getParams()); - var type = new Definition.SugaredType( - typeName, - args, - irBody.reverse(), - getIdentifiedLocation(inputAst), - meta() - ); + var type = + new Definition.SugaredType( + typeName, args, irBody.reverse(), getIdentifiedLocation(inputAst), meta()); yield join(type, appendTo); } @@ -252,14 +253,15 @@ private List translateModuleSymbolImpl(Tree inputAst, List { - var annotation = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), - getIdentifiedLocation(anno), meta()); + var annotation = + new Name.BuiltinAnnotation( + "@" + anno.getAnnotation().codeRepr(), getIdentifiedLocation(anno), meta()); yield translateModuleSymbol(anno.getExpression(), join(annotation, appendTo)); } @@ -288,13 +290,14 @@ private Expression translateForeignFunction(Tree.ForeignFunction fn) throws Synt var language = languageName; if (language == null) { var message = "Language '" + languageName + "' is not a supported polyglot language."; - return translateSyntaxError(fn, new Syntax.InvalidForeignDefinition(message)); + return translateSyntaxError(fn, new Syntax.InvalidForeignDefinition(message)); } String text; if (fn.getBody() instanceof Tree.TextLiteral body) { text = buildTextConstant(body, body.getElements()); } else { - return translateSyntaxError(fn, new Syntax.InvalidForeignDefinition("Expected text literal as body")); + return translateSyntaxError( + fn, new Syntax.InvalidForeignDefinition("Expected text literal as body")); } return Foreign.Definition.builder() .lang(language) @@ -324,15 +327,14 @@ List translateConstructorDefinition(Tree.ConstructorDefinition cons, List args = new ArrayList<>(); try { - for (var arg : cons.getArguments()) - args.add(translateArgumentDefinition(arg)); + for (var arg : cons.getArguments()) args.add(translateArgumentDefinition(arg)); for (var argLine : cons.getBlock()) { if (argLine.getArgument() instanceof ArgumentDefinition arg) args.add(translateArgumentDefinition(arg)); @@ -379,7 +381,8 @@ private List translateTypeBodyExpressionImpl(Tree exp, List appendTo) yield join(ir, appendTo); } - case Tree.TypeSignatureDeclaration sig -> join(translateTypeSignature(sig.getSignature()), appendTo); + case Tree.TypeSignatureDeclaration sig -> + join(translateTypeSignature(sig.getSignature()), appendTo); case Tree.Function fun -> translateTypeMethodBinding(fun, appendTo); @@ -387,14 +390,15 @@ private List translateTypeBodyExpressionImpl(Tree exp, List appendTo) var name = buildName(fn.getName()); var args = translateArgumentsDefinition(fn.getArgs()); var def = translateForeignFunction(fn); - var binding = Function.Binding.builder() - .name(name) - .arguments(args) - .body(def) - .isPrivate(false) - .canBeTCO(true) - .location(getIdentifiedLocation(fn)) - .build(); + var binding = + Function.Binding.builder() + .name(name) + .arguments(args) + .body(def) + .isPrivate(false) + .canBeTCO(true) + .location(getIdentifiedLocation(fn)) + .build(); yield join(binding, appendTo); } @@ -407,8 +411,9 @@ private List translateTypeBodyExpressionImpl(Tree exp, List appendTo) } case Tree.AnnotatedBuiltin anno -> { - var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), - getIdentifiedLocation(anno), meta()); + var ir = + new Name.BuiltinAnnotation( + "@" + anno.getAnnotation().codeRepr(), getIdentifiedLocation(anno), meta()); var annotation = translateBuiltinAnnotation(ir, anno.getExpression(), nil()); yield join(annotation, appendTo); } @@ -428,15 +433,15 @@ private Application translateTypeApplication(Tree.App app) throws SyntaxExceptio while (t instanceof Tree.App tApp) { var typeArg = translateTypeCallArgument(tApp.getArg()); if (typeArg.value() instanceof Name.Literal l && "in".equals(l.name())) { - in = l.copy( - l.copy$default$1(), - true, - l.copy$default$3(), - l.copy$default$4(), - l.copy$default$5(), - l.copy$default$6(), - l.copy$default$7() - ); + in = + l.copy( + l.copy$default$1(), + true, + l.copy$default$3(), + l.copy$default$4(), + l.copy$default$5(), + l.copy$default$6(), + l.copy$default$7()); } else { args = join(typeArg, args); } @@ -444,30 +449,34 @@ private Application translateTypeApplication(Tree.App app) throws SyntaxExceptio } var fullQualifiedNames = qualifiedNameSegments(t, false).reverse(); var segments = fullQualifiedNames.length(); - var type = switch (segments) { - case 1 -> fullQualifiedNames.head(); - default -> { - var name = fullQualifiedNames.head(); - name = new Name.Literal(name.name(), true, name.identifiedLocation(), Option.empty(), name.passData()); - List tail = (List) fullQualifiedNames.tail(); - tail = tail.reverse(); - final IdentifiedLocation loc = getIdentifiedLocation(app); - Name arg; - if (segments == 2) { - arg = tail.head(); - } else { - arg = new Name.Qualified(tail, loc, meta()); - } - var ca = CallArgument.Specified.builder() - .name(Option.empty()) - .value(arg) - .isSynthetic(false) - .location(loc) - .build(); - args = join(ca, args); - yield name; - } - }; + var type = + switch (segments) { + case 1 -> fullQualifiedNames.head(); + default -> { + var name = fullQualifiedNames.head(); + name = + new Name.Literal( + name.name(), true, name.identifiedLocation(), Option.empty(), name.passData()); + List tail = (List) fullQualifiedNames.tail(); + tail = tail.reverse(); + final IdentifiedLocation loc = getIdentifiedLocation(app); + Name arg; + if (segments == 2) { + arg = tail.head(); + } else { + arg = new Name.Qualified(tail, loc, meta()); + } + var ca = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(arg) + .isSynthetic(false) + .location(loc) + .build(); + args = join(ca, args); + yield name; + } + }; if (in == null) { return Application.Prefix.builder() .function(type) @@ -476,23 +485,25 @@ private Application translateTypeApplication(Tree.App app) throws SyntaxExceptio .location(getIdentifiedLocation(app)) .build(); } else { - var fn = CallArgument.Specified.builder() - .name(Option.empty()) - .value(type) - .isSynthetic(false) - .location(getIdentifiedLocation(app)) - .build(); + var fn = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(type) + .isSynthetic(false) + .location(getIdentifiedLocation(app)) + .build(); return new Operator.Binary(fn, in, args.head(), getIdentifiedLocation(app), meta()); } } private Definition translateAnnotation(FunctionAnnotation anno) { if (anno.getArgument() == null) { - return translateSyntaxError(getIdentifiedLocation(anno), Syntax.UnexpectedExpression$.MODULE$); + return translateSyntaxError( + getIdentifiedLocation(anno), Syntax.UnexpectedExpression$.MODULE$); } else { var annotationArgument = translateExpression(anno.getArgument()); - return new Name.GenericAnnotation(anno.getAnnotation().codeRepr(), - annotationArgument, getIdentifiedLocation(anno), meta()); + return new Name.GenericAnnotation( + anno.getAnnotation().codeRepr(), annotationArgument, getIdentifiedLocation(anno), meta()); } } @@ -525,14 +536,8 @@ private List translateMethodBinding(Tree.Function fn, List translateTypeMethodBinding(Tree.Function fun, List appendTo) { @@ -559,13 +564,15 @@ private Definition translateTypeSignature(TypeSignature sig) { var isMethod = name instanceof Tree.Ident ident && ident.getToken().isOperatorLexically(); var fnName = translateExpression(name, isMethod); var fnType = translateType(sig.getType()); - return new Type.Ascription(fnName, fnType, AscriptionReason.empty(), getIdentifiedLocation(sig), meta()); + return new Type.Ascription( + fnName, fnType, AscriptionReason.empty(), getIdentifiedLocation(sig), meta()); } private Definition translateMethodTypeSignature(TypeSignature sig) throws SyntaxException { var methodReference = translateMethodReference(sig.getName(), true); var signature = translateType(sig.getType()); - return new Type.Ascription(methodReference, signature, AscriptionReason.empty(), getIdentifiedLocation(sig), meta()); + return new Type.Ascription( + methodReference, signature, AscriptionReason.empty(), getIdentifiedLocation(sig), meta()); } private Expression translateFunction(Tree.Function fun) { @@ -597,7 +604,8 @@ private Expression translateFunction(Tree.Function fun) { if (body == null) { return translateSyntaxError(fun, Syntax.UnexpectedDeclarationInType$.MODULE$); } - final boolean isOperator = fun.getName() instanceof Tree.Ident ident && ident.getToken().isOperatorLexically(); + final boolean isOperator = + fun.getName() instanceof Tree.Ident ident && ident.getToken().isOperatorLexically(); if (isOperator && args.size() != 2) { return translateSyntaxError(fun, Syntax.InvalidOperator$.MODULE$); } @@ -614,9 +622,7 @@ private Expression translateFunction(Tree.Function fun) { } } - /** - * Returns the return type of a function, if it was specified inline. - */ + /** Returns the return type of a function, if it was specified inline. */ private Expression resolveReturnTypeSignature(Tree.Function fun) { var returnSignature = fun.getReturns(); if (returnSignature == null) { @@ -629,18 +635,19 @@ private Expression resolveReturnTypeSignature(Tree.Function fun) { /** * Wraps a body expression in a type ascription that will ensure that the type of the body is * checked to match the provided type. - *

- * If the type is {@code null}, the body is returned unchanged. + * + *

If the type is {@code null}, the body is returned unchanged. */ - private Expression addTypeAscription(String functionName, Expression body, Expression type, IdentifiedLocation loc) { + private Expression addTypeAscription( + String functionName, Expression body, Expression type, IdentifiedLocation loc) { if (type == null) { return body; } - return new Type.Ascription(body, type, AscriptionReason.forFunctionResult(functionName), loc, meta()); + return new Type.Ascription( + body, type, AscriptionReason.forFunctionResult(functionName), loc, meta()); } - /** * Translates a method reference from [[AST]] into [[IR]]. * @@ -686,24 +693,26 @@ private Expression translateCall(Tree ast, boolean isMethod) throws SyntaxExcept case Tree.App app -> { var expr = translateExpression(app.getArg(), false); var loc = getIdentifiedLocation(app.getArg()); - args.add(CallArgument.Specified.builder() - .name(Option.empty()) - .value(expr) - .isSynthetic(false) - .location(loc) - .build()); + args.add( + CallArgument.Specified.builder() + .name(Option.empty()) + .value(expr) + .isSynthetic(false) + .location(loc) + .build()); tree = app.getFunc(); } case Tree.NamedApp app -> { var expr = translateExpression(app.getArg(), false); var loc = getIdentifiedLocation(app.getArg()); var id = buildName(app, app.getName()); - var arg = CallArgument.Specified.builder() - .name(Option.apply(id)) - .value(expr) - .isSynthetic(false) - .location(loc) - .build(); + var arg = + CallArgument.Specified.builder() + .name(Option.apply(id)) + .value(expr) + .isSynthetic(false) + .location(loc) + .build(); args.add(arg); tree = app.getFunc(); } @@ -718,43 +727,47 @@ private Expression translateCall(Tree ast, boolean isMethod) throws SyntaxExcept if (self == null || !invoke) { return null; } - var expr = switch (translateExpression(l.getExpression().getExpression(), true)) { - case Application.Prefix pref -> { - var arg = CallArgument.Specified.builder() - .name(Option.empty()) - .value(self) - .isSynthetic(false) - .location(self.identifiedLocation()) - .build(); - yield Application.Prefix.builder() - .function(pref.function()) - .arguments(join(arg, pref.arguments())) - .hasDefaultsSuspended(false) - .location(pref.identifiedLocation()) - .build(); - } - case Expression any -> { - var arg = CallArgument.Specified.builder() + var expr = + switch (translateExpression(l.getExpression().getExpression(), true)) { + case Application.Prefix pref -> { + var arg = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(self) + .isSynthetic(false) + .location(self.identifiedLocation()) + .build(); + yield Application.Prefix.builder() + .function(pref.function()) + .arguments(join(arg, pref.arguments())) + .hasDefaultsSuspended(false) + .location(pref.identifiedLocation()) + .build(); + } + case Expression any -> { + var arg = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(self) + .isSynthetic(false) + .location(self.identifiedLocation()) + .build(); + yield Application.Prefix.builder() + .function(any) + .arguments(join(arg, nil())) + .hasDefaultsSuspended(false) + .location(any.identifiedLocation()) + .build(); + } + }; + var loc = getIdentifiedLocation(l.getExpression().getExpression()); + var arg = + CallArgument.Specified.builder() .name(Option.empty()) - .value(self) + .value(expr) .isSynthetic(false) - .location(self.identifiedLocation()) - .build(); - yield Application.Prefix.builder() - .function(any) - .arguments(join(arg, nil())) - .hasDefaultsSuspended(false) - .location(any.identifiedLocation()) + .location(loc) .build(); - } - }; - var loc = getIdentifiedLocation(l.getExpression().getExpression()); - var arg = CallArgument.Specified.builder() - .name(Option.empty()) - .value(expr) - .isSynthetic(false) - .location(loc) - .build(); args.add(at, arg); self = expr; } @@ -772,12 +785,13 @@ && isDotOperator(oprApp.getOpr().getRight()) if (oprApp.getLhs() != null) { var self = translateExpression(oprApp.getLhs(), isMethod); var loc = getIdentifiedLocation(oprApp.getLhs()); - var arg = CallArgument.Specified.builder() - .name(Option.empty()) - .value(self) - .isSynthetic(false) - .location(loc) - .build(); + var arg = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(self) + .isSynthetic(false) + .location(loc) + .build(); args.add(arg); } } else if (args.isEmpty()) { @@ -798,13 +812,12 @@ && isDotOperator(oprApp.getOpr().getRight()) } } - private Name translateOldStyleLambdaArgumentName(Tree arg, boolean[] suspended, - Expression[] defaultValue) throws SyntaxException { + private Name translateOldStyleLambdaArgumentName( + Tree arg, boolean[] suspended, Expression[] defaultValue) throws SyntaxException { return switch (arg) { case Tree.Group g -> translateOldStyleLambdaArgumentName(g.getBody(), suspended, defaultValue); - case Tree.Wildcard wild -> - new Name.Blank(getIdentifiedLocation(wild.getToken()), meta()); + case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild.getToken()), meta()); case Tree.OprApp app when "=".equals(app.getOpr().getRight().codeRepr()) -> { if (defaultValue != null) { defaultValue[0] = translateExpression(app.getRhs(), false); @@ -900,7 +913,8 @@ yield switch (op.codeRepr()) { } case "->" -> { - // Old-style lambdas; this syntax will be eliminated after the parser transition is complete. + // Old-style lambdas; this syntax will be eliminated after the parser transition is + // complete. var arg = app.getLhs(); if (arg == null) { yield translateSyntaxError(app, Syntax.UnexpectedExpression$.MODULE$); @@ -912,28 +926,26 @@ yield switch (op.codeRepr()) { } var defaultValue = new Expression[1]; Name name = translateOldStyleLambdaArgumentName(arg, isSuspended, defaultValue); - var arg_ = Specified.builder() - .name(name) - .ascribedType(Option.empty()) - .defaultValue(Option.apply(defaultValue[0])) - .suspended(isSuspended[0]) - .location(getIdentifiedLocation(arg)) - .build(); + var arg_ = + Specified.builder() + .name(name) + .ascribedType(Option.empty()) + .defaultValue(Option.apply(defaultValue[0])) + .suspended(isSuspended[0]) + .location(getIdentifiedLocation(arg)) + .build(); List args = join(arg_, nil()); var body = translateExpression(app.getRhs(), false); if (body == null) { - body = new Expression.Block( - nil(), - new Name.Blank(null, meta()), - null, - true, - meta() - ); + body = new Expression.Block(nil(), new Name.Blank(null, meta()), null, true, meta()); } - var at = expandToContain(switch (body) { - case Expression.Block __ -> getIdentifiedLocation(tree, 0, 1, null); - default -> getIdentifiedLocation(tree); - }, body.identifiedLocation()); + var at = + expandToContain( + switch (body) { + case Expression.Block __ -> getIdentifiedLocation(tree, 0, 1, null); + default -> getIdentifiedLocation(tree); + }, + body.identifiedLocation()); yield Function.Lambda.builder() .arguments(args) .bodyReference(Persistance.Reference.of(body)) @@ -957,19 +969,20 @@ yield switch (op.codeRepr()) { for (var l : app.getExpressions()) { var op = l.getExpression().getOperator().getRight(); if (op == null || isDotOperator(op)) { - yield translateSyntaxError(l.getExpression().getExpression(), - Syntax.UnexpectedExpression$.MODULE$); + yield translateSyntaxError( + l.getExpression().getExpression(), Syntax.UnexpectedExpression$.MODULE$); } var rhs = unnamedCallArgument(l.getExpression().getExpression()); var loc = getIdentifiedLocation(app); var both = applyOperator(op, lhs, rhs, loc); expr = both; - lhs = CallArgument.Specified.builder() - .name(Option.empty()) - .value(expr) - .isSynthetic(false) - .location(loc) - .build(); + lhs = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(expr) + .isSynthetic(false) + .location(loc) + .build(); } yield expr; } @@ -1045,7 +1058,8 @@ yield translateSyntaxError(l.getExpression().getExpression(), last = new Name.Blank(null, meta()); } var block = - new Expression.Block(expressions.reverse(), last, getIdentifiedLocation(body), false, meta()); + new Expression.Block( + expressions.reverse(), last, getIdentifiedLocation(body), false, meta()); if (body.getLhs() != null) { var fn = translateExpression(body.getLhs(), isMethod); List args = nil(); @@ -1069,7 +1083,8 @@ yield switch (fn) { yield switch (translateExpression(group.getBody(), false)) { case null -> translateSyntaxError(group, Syntax.EmptyParentheses$.MODULE$); case Application.Prefix pref -> { - final IdentifiedLocation groupWithoutParenthesis = getIdentifiedLocation(group, 1, -1, pref.getExternalId()); + final IdentifiedLocation groupWithoutParenthesis = + getIdentifiedLocation(group, 1, -1, pref.getExternalId()); yield pref.setLocation(Option.apply(groupWithoutParenthesis)); } case Expression in -> in; @@ -1094,23 +1109,26 @@ yield switch (translateExpression(group.getBody(), false)) { var comment = translateComment(cas, docLine.getDocs()); var loc = getIdentifiedLocation(cas); var doc = new Pattern.Documentation(comment.doc(), loc, meta()); - var br = Case.Branch.builder() - .pattern(doc) - .expression(new Empty(null, meta())) - .terminalBranch(true) - .location(loc) - .build(); + var br = + Case.Branch.builder() + .pattern(doc) + .expression(new Empty(null, meta())) + .terminalBranch(true) + .location(loc) + .build(); branches = join(br, branches); } - // A branch with no expression is used to hold any orphaned documentation at the end of the case-of + // A branch with no expression is used to hold any orphaned documentation at the end of + // the case-of // expression, with no case to attach it to. if (branch.getExpression() != null) { - var br = Case.Branch.builder() - .pattern(translatePattern(branch.getPattern())) - .expression(translateExpression(branch.getExpression(), false)) - .terminalBranch(true) - .location(getIdentifiedLocation(branch.getExpression())) - .build(); + var br = + Case.Branch.builder() + .pattern(translatePattern(branch.getPattern())) + .expression(translateExpression(branch.getExpression(), false)) + .terminalBranch(true) + .location(getIdentifiedLocation(branch.getExpression())) + .build(); branches = join(br, branches); } } @@ -1125,22 +1143,23 @@ yield switch (translateExpression(group.getBody(), false)) { case Tree.OprSectionBoundary bound -> translateExpression(bound.getAst(), false); case Tree.UnaryOprApp un when "-".equals(un.getOpr().codeRepr()) -> switch (translateExpression(un.getRhs(), false)) { - case Literal.Number n -> n.copy( - n.copy$default$1(), - "-" + n.copy$default$2(), - Option.apply(getIdentifiedLocation(un)), - n.copy$default$4(), - n.copy$default$5(), - n.copy$default$6() - ); + case Literal.Number n -> + n.copy( + n.copy$default$1(), + "-" + n.copy$default$2(), + Option.apply(getIdentifiedLocation(un)), + n.copy$default$4(), + n.copy$default$5(), + n.copy$default$6()); case Expression expr -> { var negate = new Name.Literal("negate", true, null, Option.empty(), meta()); - var arg = CallArgument.Specified.builder() - .name(Option.empty()) - .value(expr) - .isSynthetic(false) - .location(expr.identifiedLocation()) - .build(); + var arg = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(expr) + .isSynthetic(false) + .location(expr.identifiedLocation()) + .build(); yield Application.Prefix.builder() .function(negate) .arguments(join(arg, nil())) @@ -1154,8 +1173,9 @@ yield switch (translateExpression(group.getBody(), false)) { case Tree.TemplateFunction templ -> translateExpression(templ.getAst(), false); case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild), meta()); case Tree.AnnotatedBuiltin anno -> { - var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), - getIdentifiedLocation(anno), meta()); + var ir = + new Name.BuiltinAnnotation( + "@" + anno.getAnnotation().codeRepr(), getIdentifiedLocation(anno), meta()); yield translateBuiltinAnnotation(ir, anno.getExpression(), nil()); } @@ -1176,11 +1196,7 @@ yield switch (translateExpression(group.getBody(), false)) { case Tree.AutoscopedIdentifier autoscopedIdentifier -> { var methodName = buildName(autoscopedIdentifier.getIdent()); yield new Name.MethodReference( - Option.empty(), - methodName, - getIdentifiedLocation(autoscopedIdentifier), - meta() - ); + Option.empty(), methodName, getIdentifiedLocation(autoscopedIdentifier), meta()); } case Tree.Invalid __ -> translateSyntaxError(tree, Syntax.UnexpectedExpression$.MODULE$); default -> translateSyntaxError(tree, new Syntax.UnsupportedSyntax("translateExpression")); @@ -1194,15 +1210,17 @@ private Expression translateTypeSignatureToOprApp(TypeSignature sig) { } catch (SyntaxException ex) { return ex.toError(); } - var methodReference = CallArgument.Specified.builder() - .name(Option.empty()) - .value(methodName) - .isSynthetic(false) - .location(methodName.identifiedLocation()) - .build(); + var methodReference = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(methodName) + .isSynthetic(false) + .location(methodName.identifiedLocation()) + .build(); var opName = buildName(null, sig.getOperator(), true); var signature = translateTypeCallArgument(sig.getType()); - return new Operator.Binary(methodReference, opName, signature, getIdentifiedLocation(sig), meta()); + return new Operator.Binary( + methodReference, opName, signature, getIdentifiedLocation(sig), meta()); } private Expression.Block translateBodyBlock(Tree.BodyBlock body, boolean suspended) { @@ -1223,8 +1241,8 @@ private Expression.Block translateBodyBlock(Tree.BodyBlock body, boolean suspend } var list = CollectionConverters.asScala(expressions.iterator()).toList(); if (last != null - && last.location().isDefined() - && last.location().get().end() != locationWithANewLine.end()) { + && last.location().isDefined() + && last.location().get().end() != locationWithANewLine.end()) { int start = last.location().get().start(); int end = locationWithANewLine.end() - 1; var id = new IdentifiedLocation(start, end, last.location().get().uuid()); @@ -1260,7 +1278,7 @@ private void translateBlockStatement(Tree tree, Collection appendTo) appendTo.add(comment); } for (var annoLine : fun.getAnnotationLines()) { - appendTo.add((Expression)translateAnnotation(annoLine.getAnnotation())); + appendTo.add((Expression) translateAnnotation(annoLine.getAnnotation())); } if (fun.getSignatureLine() instanceof TypeSignatureLine sigLine) { appendTo.add(translateTypeSignatureToOprApp(sigLine.getSignature())); @@ -1321,10 +1339,10 @@ private void attachTranslatedWarnings(IR ir, Tree tree) { } } - private Operator applyOperator(Token.Operator op, CallArgument lhs, CallArgument rhs, IdentifiedLocation loc) { - var name = new Name.Literal( - op.codeRepr(), true, getIdentifiedLocation(op), Option.empty(), meta() - ); + private Operator applyOperator( + Token.Operator op, CallArgument lhs, CallArgument rhs, IdentifiedLocation loc) { + var name = + new Name.Literal(op.codeRepr(), true, getIdentifiedLocation(op), Option.empty(), meta()); if (lhs == null && rhs == null) { return new Section.Sides(name, loc, meta()); } else if (lhs == null) { @@ -1341,52 +1359,54 @@ Tree applySkip(Tree tree) { // Every iteration either breaks, or reduces [`tree`] to a substructure of [`tree`]. var done = false; while (!done && tree != null) { - tree = switch (tree) { - case Tree.MultiSegmentApp app - when FREEZE_MACRO_IDENTIFIER.equals(app.getSegments().get(0).getHeader().codeRepr()) -> - app.getSegments().get(0).getBody(); - case Tree.Invalid ignored -> null; - case Tree.BodyBlock ignored -> null; - case Tree.Number ignored -> null; - case Tree.Wildcard ignored -> null; - case Tree.SuspendedDefaultArguments ignored -> null; - case Tree.ForeignFunction ignored -> null; - case Tree.Import ignored -> null; - case Tree.Export ignored -> null; - case Tree.TypeDef ignored -> null; - case Tree.ArgumentBlockApplication app -> app.getLhs(); - case Tree.OperatorBlockApplication app -> app.getLhs(); - case Tree.OprApp app -> app.getLhs(); - case Tree.Ident ident when ident.getToken().isTypeOrConstructor() -> null; - case Tree.Ident ignored -> { - done = true; - yield tree; - } - case Tree.Group ignored -> { - done = true; - yield tree; - } - case Tree.UnaryOprApp app -> app.getRhs(); - case Tree.OprSectionBoundary section -> section.getAst(); - case Tree.TemplateFunction function -> function.getAst(); - case Tree.AnnotatedBuiltin annotated -> annotated.getExpression(); - case Tree.ExpressionStatement statement -> statement.getExpression(); - case Tree.Assignment assignment -> assignment.getExpr(); - case Tree.TypeAnnotated annotated -> annotated.getExpression(); - case Tree.App app when isApplication(app.getFunc()) -> app.getFunc(); - case Tree.NamedApp app when isApplication(app.getFunc()) -> app.getFunc(); - case Tree.App app -> useOrElse(applySkip(app.getFunc()), app.getArg()); - case Tree.NamedApp app -> useOrElse(applySkip(app.getFunc()), app.getArg()); - case Tree.MultiSegmentApp ignored -> null; - case Tree.TextLiteral ignored -> null; - case Tree.Function ignored -> null; - case Tree.Lambda ignored -> null; - case Tree.CaseOf ignored -> null; - case Tree.Array ignored -> null; - case Tree.Tuple ignored -> null; - case Tree.Documentation ignored -> null; - default -> null; - }; + tree = + switch (tree) { + case Tree.MultiSegmentApp app + when FREEZE_MACRO_IDENTIFIER.equals( + app.getSegments().get(0).getHeader().codeRepr()) -> + app.getSegments().get(0).getBody(); + case Tree.Invalid ignored -> null; + case Tree.BodyBlock ignored -> null; + case Tree.Number ignored -> null; + case Tree.Wildcard ignored -> null; + case Tree.SuspendedDefaultArguments ignored -> null; + case Tree.ForeignFunction ignored -> null; + case Tree.Import ignored -> null; + case Tree.Export ignored -> null; + case Tree.TypeDef ignored -> null; + case Tree.ArgumentBlockApplication app -> app.getLhs(); + case Tree.OperatorBlockApplication app -> app.getLhs(); + case Tree.OprApp app -> app.getLhs(); + case Tree.Ident ident when ident.getToken().isTypeOrConstructor() -> null; + case Tree.Ident ignored -> { + done = true; + yield tree; + } + case Tree.Group ignored -> { + done = true; + yield tree; + } + case Tree.UnaryOprApp app -> app.getRhs(); + case Tree.OprSectionBoundary section -> section.getAst(); + case Tree.TemplateFunction function -> function.getAst(); + case Tree.AnnotatedBuiltin annotated -> annotated.getExpression(); + case Tree.ExpressionStatement statement -> statement.getExpression(); + case Tree.Assignment assignment -> assignment.getExpr(); + case Tree.TypeAnnotated annotated -> annotated.getExpression(); + case Tree.App app when isApplication(app.getFunc()) -> app.getFunc(); + case Tree.NamedApp app when isApplication(app.getFunc()) -> app.getFunc(); + case Tree.App app -> useOrElse(applySkip(app.getFunc()), app.getArg()); + case Tree.NamedApp app -> useOrElse(applySkip(app.getFunc()), app.getArg()); + case Tree.MultiSegmentApp ignored -> null; + case Tree.TextLiteral ignored -> null; + case Tree.Function ignored -> null; + case Tree.Lambda ignored -> null; + case Tree.CaseOf ignored -> null; + case Tree.Array ignored -> null; + case Tree.Tuple ignored -> null; + case Tree.Documentation ignored -> null; + default -> null; + }; } return tree; } @@ -1427,26 +1447,25 @@ yield switch (op.codeRepr()) { var literal = translateType(app.getLhs()); var body = translateType(app.getRhs()); if (body == null) { - yield new Syntax(getIdentifiedLocation(app), Syntax.UnexpectedExpression$.MODULE$, meta()); + yield new Syntax( + getIdentifiedLocation(app), Syntax.UnexpectedExpression$.MODULE$, meta()); } - var args = switch (body) { - case Type.Function fn -> { - body = fn.result(); - yield join(literal, fn.args()); - } - default -> join(literal, nil()); - }; + var args = + switch (body) { + case Type.Function fn -> { + body = fn.result(); + yield join(literal, fn.args()); + } + default -> join(literal, nil()); + }; yield new Type.Function(args, body, null, meta()); } default -> { var lhs = translateTypeCallArgument(app.getLhs()); var rhs = translateTypeCallArgument(app.getRhs()); - var name = new Name.Literal( - op.codeRepr(), true, - getIdentifiedLocation(app), - Option.empty(), - meta() - ); + var name = + new Name.Literal( + op.codeRepr(), true, getIdentifiedLocation(app), Option.empty(), meta()); var loc = getIdentifiedLocation(app); yield new Operator.Binary(lhs, name, rhs, loc, meta()); } @@ -1476,13 +1495,12 @@ yield switch (op.codeRepr()) { }; } - /** - * Translate a type-annotated expression. - */ + /** Translate a type-annotated expression. */ Expression translateTypeAnnotated(Tree.TypeAnnotated anno) { var type = translateType(anno.getType()); var expr = translateExpression(anno.getExpression()); - return new Type.Ascription(expr, type, AscriptionReason.empty(), getIdentifiedLocation(anno), meta()); + return new Type.Ascription( + expr, type, AscriptionReason.empty(), getIdentifiedLocation(anno), meta()); } /** @@ -1491,18 +1509,14 @@ Expression translateTypeAnnotated(Tree.TypeAnnotated anno) { Expression translateTypeAnnotatedToOperator(Tree.TypeAnnotated anno) { var type = translateTypeCallArgument(anno.getType()); var expr = translateCallArgument(anno.getExpression()); - var opName = new Name.Literal(anno.getOperator().codeRepr(), true, null, Option.empty(), meta()); - return new Operator.Binary( - expr, - opName, - type, - getIdentifiedLocation(anno), - meta()); + var opName = + new Name.Literal(anno.getOperator().codeRepr(), true, null, Option.empty(), meta()); + return new Operator.Binary(expr, opName, type, getIdentifiedLocation(anno), meta()); } @SuppressWarnings("unchecked") - private Expression patchPrefixWithBlock(Application.Prefix pref, Expression.Block block, - List args) { + private Expression patchPrefixWithBlock( + Application.Prefix pref, Expression.Block block, List args) { if (block.expressions().isEmpty() && block.returnValue() instanceof Name.Blank) { return pref; } @@ -1510,12 +1524,13 @@ private Expression patchPrefixWithBlock(Application.Prefix pref, Expression.Bloc args = (List) args.tail(); } List allArgs = (List) pref.arguments().appendedAll(args.reverse()); - final CallArgument.Specified blockArg = CallArgument.Specified.builder() - .name(Option.empty()) - .value(block) - .isSynthetic(false) - .location(block.identifiedLocation()) - .build(); + final CallArgument.Specified blockArg = + CallArgument.Specified.builder() + .name(Option.empty()) + .value(block) + .isSynthetic(false) + .location(block.identifiedLocation()) + .build(); List withBlockArgs = (List) allArgs.appended(blockArg); if (!checkArgs(withBlockArgs)) { return translateSyntaxError(pref.location().get(), Syntax.UnexpectedExpression$.MODULE$); @@ -1528,8 +1543,8 @@ private Expression patchPrefixWithBlock(Application.Prefix pref, Expression.Bloc .build(); } - private Application.Prefix translateBuiltinAnnotation(Name.BuiltinAnnotation ir, Tree expr, - List callArgs) { + private Application.Prefix translateBuiltinAnnotation( + Name.BuiltinAnnotation ir, Tree expr, List callArgs) { return switch (expr) { case Tree.App fn -> { var fnAsArg = translateCallArgument(fn.getArg()); @@ -1545,12 +1560,13 @@ private Application.Prefix translateBuiltinAnnotation(Name.BuiltinAnnotation ir, callArgs = join(fnAsArg, join(arg, callArgs)); yield translateBuiltinAnnotation(ir, null, callArgs); } - case null -> Application.Prefix.builder() - .function(ir) - .arguments(callArgs) - .hasDefaultsSuspended(false) - .location(ir.identifiedLocation()) - .build(); + case null -> + Application.Prefix.builder() + .function(ir) + .arguments(callArgs) + .hasDefaultsSuspended(false) + .location(ir.identifiedLocation()) + .build(); default -> { var arg = translateCallArgument(expr); callArgs = join(arg, callArgs); @@ -1561,26 +1577,30 @@ private Application.Prefix translateBuiltinAnnotation(Name.BuiltinAnnotation ir, Expression translateNumber(Tree.Number ast) { var intPart = ast.getInteger(); - final Option base = switch (intPart.getBase()) { - case Base.Binary b -> Option.apply("2"); - case Base.Hexadecimal b -> Option.apply("16"); - case Base.Octal b -> Option.apply("8"); - case null -> Option.empty(); - default -> Option.empty(); - }; + final Option base = + switch (intPart.getBase()) { + case Base.Binary b -> Option.apply("2"); + case Base.Hexadecimal b -> Option.apply("16"); + case Base.Octal b -> Option.apply("8"); + case null -> Option.empty(); + default -> Option.empty(); + }; var fracPart = ast.getFractionalDigits(); - String literal = fracPart != null ? intPart.codeRepr() + "." + fracPart.getDigits().codeRepr() - : intPart.codeRepr(); + String literal = + fracPart != null + ? intPart.codeRepr() + "." + fracPart.getDigits().codeRepr() + : intPart.codeRepr(); return new Literal.Number(base, literal, getIdentifiedLocation(ast), meta()); } Literal translateLiteral(Tree.TextLiteral txt) throws SyntaxException { if (txt.getClose() == null) { - if (txt.getOpen() == null || switch (txt.getOpen().codeRepr()) { - case "'''" -> false; - case "\"\"\"" -> false; - default -> true; - }) { + if (txt.getOpen() == null + || switch (txt.getOpen().codeRepr()) { + case "'''" -> false; + case "\"\"\"" -> false; + default -> true; + }) { throw new SyntaxException(txt, Syntax.UnclosedTextLiteral$.MODULE$); } } @@ -1613,7 +1633,6 @@ private String buildTextConstant(Tree at, Iterable elements) throws return sb.toString(); } - /** * Translates an argument definition from [[AST]] into [[IR]]. * @@ -1622,25 +1641,26 @@ private String buildTextConstant(Tree at, Iterable elements) throws */ DefinitionArgument translateArgumentDefinition(ArgumentDefinition def) throws SyntaxException { Tree pattern = def.getPattern(); - Name name = switch (pattern) { - case Tree.Wildcard wild -> - new Name.Blank(getIdentifiedLocation(wild.getToken()), meta()); - case Tree.Ident id -> { - Expression identifier = translateIdent(id, false); - yield switch (identifier) { - case Name name_ -> name_; + Name name = + switch (pattern) { + case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild.getToken()), meta()); + case Tree.Ident id -> { + Expression identifier = translateIdent(id, false); + yield switch (identifier) { + case Name name_ -> name_; + // TODO: Other types of pattern. Needs IR support. + default -> throw translateEntity(pattern, "translateArgumentDefinition"); + }; + } // TODO: Other types of pattern. Needs IR support. default -> throw translateEntity(pattern, "translateArgumentDefinition"); }; - } - // TODO: Other types of pattern. Needs IR support. - default -> throw translateEntity(pattern, "translateArgumentDefinition"); - }; boolean isSuspended = def.getSuspension() != null; - var ascribedType = Option.apply(def.getType()) - .map(ascription -> translateType(ascription.getType())); - var defaultValue = Option.apply(def.getDefault()) - .map(default_ -> translateExpression(default_.getExpression(), false)); + var ascribedType = + Option.apply(def.getType()).map(ascription -> translateType(ascription.getType())); + var defaultValue = + Option.apply(def.getDefault()) + .map(default_ -> translateExpression(default_.getExpression(), false)); return DefinitionArgument.Specified.builder() .name(name) .ascribedType(ascribedType) @@ -1734,17 +1754,12 @@ Pattern translatePattern(Tree block) throws SyntaxException { return switch (elements.get(0)) { case Tree.Ident id when id.getToken().isTypeOrConstructor() || !fields.isEmpty() -> { yield new Pattern.Constructor( - sanitizeName(buildName(id)), fields, - getIdentifiedLocation(id), meta() - ); + sanitizeName(buildName(id)), fields, getIdentifiedLocation(id), meta()); } - case Tree.Ident id -> - new Pattern.Name(buildName(id), getIdentifiedLocation(id), meta()); + case Tree.Ident id -> new Pattern.Name(buildName(id), getIdentifiedLocation(id), meta()); case Tree.OprApp app when isDotOperator(app.getOpr().getRight()) -> { var qualifiedName = buildQualifiedName(app); - yield new Pattern.Constructor( - qualifiedName, fields, getIdentifiedLocation(app), meta() - ); + yield new Pattern.Constructor(qualifiedName, fields, getIdentifiedLocation(app), meta()); } case Tree.Wildcard wild -> translateWildcardPattern(wild); case Tree.TextLiteral lit -> @@ -1754,14 +1769,14 @@ qualifiedName, fields, getIdentifiedLocation(app), meta() case Tree.UnaryOprApp num when num.getOpr().codeRepr().equals("-") -> { var n = (Literal.Number) translateExpression(num.getRhs()); var loc = getIdentifiedLocation(num); - var t = n.copy( - n.copy$default$1(), - "-" + n.copy$default$2(), - Option.apply(loc), - n.copy$default$4(), - n.copy$default$5(), - n.copy$default$6() - ); + var t = + n.copy( + n.copy$default$1(), + "-" + n.copy$default$2(), + Option.apply(loc), + n.copy$default$4(), + n.copy$default$5(), + n.copy$default$6()); yield new Pattern.Literal(t, loc, meta()); } case Tree.TypeAnnotated anno -> { @@ -1794,7 +1809,8 @@ private Name.Qualified buildQualifiedName(Tree t) throws SyntaxException { return buildQualifiedName(t, null, false); } - private Name.Qualified buildQualifiedName(Tree t, IdentifiedLocation loc, boolean generateId) throws SyntaxException { + private Name.Qualified buildQualifiedName(Tree t, IdentifiedLocation loc, boolean generateId) + throws SyntaxException { return new Name.Qualified(qualifiedNameSegments(t, generateId), loc, meta()); } @@ -1858,16 +1874,17 @@ private List qualifiedNameSegments(Tree t, boolean generateId) throws Synt List result = nil(); var first = true; for (var segment : unrollOprRhs(t, ".")) { - var qns = switch (qualifiedNameSegment(segment, generateId)) { - case Name.Blank underscore -> { - if (first) { - yield underscore; - } else { - throw new SyntaxException(segment, Syntax.InvalidUnderscore$.MODULE$); - } - } - case Name any -> any; - }; + var qns = + switch (qualifiedNameSegment(segment, generateId)) { + case Name.Blank underscore -> { + if (first) { + yield underscore; + } else { + throw new SyntaxException(segment, Syntax.InvalidUnderscore$.MODULE$); + } + } + case Name any -> any; + }; result = join(qns, result); first = false; } @@ -1909,8 +1926,7 @@ Import translateImport(Tree.Import imp) { new Polyglot.Java(pkg.toString(), cls), rename.map(name -> name.name()), getIdentifiedLocation(imp), - meta() - ); + meta()); } var isAll = imp.getAll() != null; Name.Qualified qualifiedName; @@ -1930,11 +1946,14 @@ Import translateImport(Tree.Import imp) { hidingNames = Option.apply(buildNameSequence(imp.getHiding().getBody())); } return new Import.Module( - qualifiedName, rename, isAll || onlyNames.isDefined() || hidingNames.isDefined(), + qualifiedName, + rename, + isAll || onlyNames.isDefined() || hidingNames.isDefined(), onlyNames, - hidingNames, false, getIdentifiedLocation(imp), - meta() - ); + hidingNames, + false, + getIdentifiedLocation(imp), + meta()); } catch (SyntaxException err) { if (err.where instanceof Tree.Invalid invalid) { return err.toError(invalidImportReason(invalid.getError())); @@ -1945,13 +1964,11 @@ hidingNames, false, getIdentifiedLocation(imp), } private Syntax.Reason invalidImportReason(String msg) { - return new Syntax.InvalidImport( - useOrElse(msg, "Imports must have a valid module path")); + return new Syntax.InvalidImport(useOrElse(msg, "Imports must have a valid module path")); } private Syntax.Reason invalidExportReason(String msg) { - return new Syntax.InvalidExport( - useOrElse(msg, "Exports must have a valid module path")); + return new Syntax.InvalidExport(useOrElse(msg, "Exports must have a valid module path")); } @SuppressWarnings("unchecked") @@ -1995,10 +2012,7 @@ Export translateExport(Tree.Export exp) { qualifiedName = buildQualifiedName(exp.getExport().getBody(), null, true); } return new Export.Module( - qualifiedName, rename, onlyNames, - getIdentifiedLocation(exp), false, - meta() - ); + qualifiedName, rename, onlyNames, getIdentifiedLocation(exp), false, meta()); } catch (SyntaxException err) { if (err.where instanceof Tree.Invalid invalid) { return err.toError(invalidExportReason(invalid.getError())); @@ -2077,11 +2091,10 @@ private Name sanitizeName(Name.Literal id) { }; } - private IdentifiedLocation expandToContain(IdentifiedLocation encapsulating, IdentifiedLocation inner) { - if (encapsulating == null) - return inner; - if (inner == null) - return encapsulating; + private IdentifiedLocation expandToContain( + IdentifiedLocation encapsulating, IdentifiedLocation inner) { + if (encapsulating == null) return inner; + if (inner == null) return encapsulating; if (encapsulating.start() > inner.start() || encapsulating.end() < inner.end()) { var start = Math.min(encapsulating.start(), inner.start()); @@ -2109,7 +2122,9 @@ private IdentifiedLocation getIdentifiedLocation(Tree ast, int b, int e, Option< var begin = castToInt(ast.getStartCode()) + b; var end = castToInt(ast.getEndCode()) + e; var location = new Location(begin, end); - var uuid = idMap.getOrDefault(location, someId == null ? ast.uuid() : someId.getOrElse(() -> null)); + var uuid = + idMap.getOrDefault( + location, someId == null ? ast.uuid() : someId.getOrElse(() -> null)); yield new IdentifiedLocation(begin, end, uuid); } }; @@ -2127,7 +2142,8 @@ private IdentifiedLocation getIdentifiedLocation(FunctionAnnotation anno) { } private IdentifiedLocation getIdentifiedLocation(TypeSignature sig) { - return expandToContain(getIdentifiedLocation(sig.getName()), getIdentifiedLocation(sig.getType())); + return expandToContain( + getIdentifiedLocation(sig.getName()), getIdentifiedLocation(sig.getType())); } private IdentifiedLocation getIdentifiedLocation(Token ast) { @@ -2163,8 +2179,8 @@ private static final scala.collection.immutable.List nil() { return (scala.collection.immutable.List) scala.collection.immutable.Nil$.MODULE$; } - private static final scala.collection.immutable.List join(T head, - scala.collection.immutable.List tail) { + private static final scala.collection.immutable.List join( + T head, scala.collection.immutable.List tail) { return scala.collection.immutable.$colon$colon$.MODULE$.apply(head, tail); } diff --git a/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserMultiThreadedTest.java b/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserMultiThreadedTest.java index 46ed3a8e790b..bf798ee4b8ea 100644 --- a/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserMultiThreadedTest.java +++ b/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserMultiThreadedTest.java @@ -16,9 +16,9 @@ public void stressLoadFromManyThreads() throws Exception { var number = i % testCases; var code = """ - from Standard.Base import all - main = %n - """ + from Standard.Base import all + main = %n + """ .replace("%n", "" + number); cases.add( () -> { diff --git a/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserTest.java b/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserTest.java index 61cee6752048..52e933e4663d 100644 --- a/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserTest.java +++ b/engine/runtime-parser/src/test/java/org/enso/compiler/core/EnsoParserTest.java @@ -27,34 +27,43 @@ public class EnsoParserTest { @Test public void testParseMain7Foo() { - parseTest(""" - main = 7.foo - """); + parseTest( + """ + main = 7.foo + """); } @Test public void testLocationsSimpleArithmeticExpression() { - parseTest(""" - main = 2 + 45 * 20 - """, true, true, true); + parseTest( + """ + main = 2 + 45 * 20 + """, + true, + true, + true); } @Test public void testLocationsApplicationsAndMethodCalls() { - parseTest(""" - main = (2-2 == 0).if_then_else (List.Cons 5 6) 0 - """, true, true, true); + parseTest( + """ + main = (2-2 == 0).if_then_else (List.Cons 5 6) 0 + """, + true, + true, + true); } @Test public void testLocationsCorrectAssignmentOfVariableReads() { parseTest( """ - main = - x = 2 + 2 * 2 - y = x * x - IO.println y - """, + main = + x = 2 + 2 * 2 + y = x * x + IO.println y + """, true, true, true); @@ -64,12 +73,12 @@ public void testLocationsCorrectAssignmentOfVariableReads() { public void testLocationsMethodWithComplexBody() { parseTest( """ - foo a b = - x : Number - x = a + 1 - y = b - 2 - x * y - """, + foo a b = + x : Number + x = a + 1 + y = b - 2 + x * y + """, true, true, true); @@ -77,37 +86,49 @@ public void testLocationsMethodWithComplexBody() { @Test public void testLocationsBuildFunctionSimple() { - parseTest(""" - main = - foo a = a + 1 - foo 42 - """, true, true, true); + parseTest( + """ + main = + foo a = a + 1 + foo 42 + """, + true, + true, + true); } @Test public void testListWithATrailingComma() { - parseTest(""" - main = ["a", ] - """, true, true, true); + parseTest( + """ + main = ["a", ] + """, + true, + true, + true); } @Test public void testLocationsDeeplyNestedFunctions() { - parseTest(""" + parseTest( + """ foo = a -> b -> IO.println a - """, true, true, true); + """, + true, + true, + true); } @Test public void testLocationsDeeplyNestedFunctionsNoBlock() { parseTest( """ - Nothing.method = - add = a -> b -> a + b + Nothing.method = + add = a -> b -> a + b - main = Nothing.method - """, + main = Nothing.method + """, true, true, true); @@ -116,326 +137,351 @@ public void testLocationsDeeplyNestedFunctionsNoBlock() { @Test public void testSpacesAtTheEndOfFile() { var fourSpaces = " "; - parseTest(""" - main = add_ten 5 - """ + fourSpaces); + parseTest( + """ + main = add_ten 5 + """ + + fourSpaces); } @Test public void testCase() { parseTest( """ - type Msg - Ahoj - Ciao - - c x = case x of - Ahoj -> 0 - Ciao -> 1 - Msg.Ciao -> 2 - """); + type Msg + Ahoj + Ciao + + c x = case x of + Ahoj -> 0 + Ciao -> 1 + Msg.Ciao -> 2 + """); } @Test public void testTypeMethodWithSignature() { parseTest( """ - @Builtin_Type - type Fuzzy - == : Correct -> Wrong - == self right = @Builtin_Method "Fuzzy.==" - """); + @Builtin_Type + type Fuzzy + == : Correct -> Wrong + == self right = @Builtin_Method "Fuzzy.==" + """); } @Test public void testImport() { parseTest( """ - import Standard.Base.Any.Any - import project.IO - import Standard.Base as Enso_List - from Standard.Base import all hiding Number, Boolean, Float, Any - polyglot java import java.lang.Float - polyglot java import java.net.URI as Java_URI - - main = 3 - """); + import Standard.Base.Any.Any + import project.IO + import Standard.Base as Enso_List + from Standard.Base import all hiding Number, Boolean, Float, Any + polyglot java import java.lang.Float + polyglot java import java.net.URI as Java_URI + + main = 3 + """); } @Test public void testImportAll() { parseTest( """ - ## TODO Dubious constructor export - from project.Network.Http.Version.Version import all - from project.Network.Http.Version.Version export all - """); + ## TODO Dubious constructor export + from project.Network.Http.Version.Version import all + from project.Network.Http.Version.Version export all + """); } @Test public void testImportTrue() { - parseTest(""" - from Standard.Base import True - """); + parseTest( + """ + from Standard.Base import True + """); } @Test public void testMeaningOfWorld() { - parseTest(""" - import Standard.Base.IO + parseTest( + """ + import Standard.Base.IO - main = IO.println 42 - """); + main = IO.println 42 + """); } @Test public void testMinusOne() { - parseTest(""" - minus n = n-1 - """); + parseTest( + """ + minus n = n-1 + """); } @Test public void testIfNothingSelf() { - parseTest(""" - if_nothing self ~_ = self - """); + parseTest( + """ + if_nothing self ~_ = self + """); } @Test public void testIfSomethingSelf() { - parseTest(""" - if_nothing self ~ignore = self - """); + parseTest( + """ + if_nothing self ~ignore = self + """); } @Test public void testMinusRec() { - parseTest(""" - minus n = minus n-1 - """); + parseTest( + """ + minus n = minus n-1 + """); } @Test public void testFactorial() { - parseTest(""" - fac n = if n == 1 then 1 else n * fac n-1 - """); + parseTest( + """ + fac n = if n == 1 then 1 else n * fac n-1 + """); } @Test public void testIsDigitWithSpaces() { - parseTest(""" - compare = - is_digit = character -> 42 - """); + parseTest( + """ + compare = + is_digit = character -> 42 + """); } @Test public void testComments() { - parseTest(""" - # a b c - """); + parseTest( + """ + # a b c + """); } @Test public void testCaseTypeOf() { - parseTest(""" - cmp self = case self of - v:Vector_2d -> x - _ -> x - """); + parseTest( + """ + cmp self = case self of + v:Vector_2d -> x + _ -> x + """); } @Test public void testCaseTypeOf2() { - parseTest(""" - cmp self = case self of - v:My_Type -> x - """); + parseTest( + """ + cmp self = case self of + v:My_Type -> x + """); } @Test public void testCaseTypeOfWithSpace() { - parseTest(""" - filter self filter = case filter of - _ : Filter -> 42 - """); + parseTest( + """ + filter self filter = case filter of + _ : Filter -> 42 + """); } @Test public void testAnnotation0() { - parseTest(""" - dont_stop = @Tail_Call dont_stop - """); + parseTest( + """ + dont_stop = @Tail_Call dont_stop + """); } @Test public void testAnnotation1() { - parseTest(""" - go t = @Tail_Call go t-1 - """); + parseTest( + """ + go t = @Tail_Call go t-1 + """); } @Test public void testAnnotation2() { - parseTest(""" - go t x = @Tail_Call go t-1 x - """); + parseTest( + """ + go t x = @Tail_Call go t-1 x + """); } @Test public void testAnnotationBlock() { - parseTest(""" - go a b = @Tail_Call go - a - b - """); + parseTest( + """ + go a b = @Tail_Call go + a + b + """); } @Test public void testBuiltinTypeAnnotation() { - parseTest(""" - @Builtin_Type - type Date - """); + parseTest( + """ + @Builtin_Type + type Date + """); } @Test public void testBoolean() { parseTest( """ - @Builtin_Type - type Boolean - True - False + @Builtin_Type + type Boolean + True + False - == : Boolean -> Boolean - == self that = @Builtin_Method "Boolean.==" + == : Boolean -> Boolean + == self that = @Builtin_Method "Boolean.==" - && : Boolean -> Boolean - && self ~that = @Builtin_Method "Boolean.&&" + && : Boolean -> Boolean + && self ~that = @Builtin_Method "Boolean.&&" - not : Boolean - not self = @Builtin_Method "Boolean.not" + not : Boolean + not self = @Builtin_Method "Boolean.not" - compare_to : Boolean -> Ordering - compare_to self that = @Builtin_Method "Boolean.compare_to" + compare_to : Boolean -> Ordering + compare_to self that = @Builtin_Method "Boolean.compare_to" - if_then_else : Any -> Any -> Any - if_then_else self ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" + if_then_else : Any -> Any -> Any + if_then_else self ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - if_then : Any -> Any | Nothing - if_then self ~on_true = @Builtin_Method "Boolean.if_then" - """); + if_then : Any -> Any | Nothing + if_then self ~on_true = @Builtin_Method "Boolean.if_then" + """); } @Test public void testBuiltinMethodAnnotation() { - parseTest(""" - normalize x = @Builtin_Method "File.normalize" - """); + parseTest( + """ + normalize x = @Builtin_Method "File.normalize" + """); } @Test public void testTextOrNothing() { - parseTest(""" - type Locale - language : Text | Nothing - """); + parseTest( + """ + type Locale + language : Text | Nothing + """); } @Test public void testInterval() { - parseTest(""" - type Interval - Interval_Data (start : Bound.Bound) - """); + parseTest( + """ + type Interval + Interval_Data (start : Bound.Bound) + """); } @Test public void testAtEq() { parseTest( """ - type Array - == : Array -> Boolean - == self that = - if False then True that else - eq_at i = self.at i == that.at i - eq_at 0 - """); + type Array + == : Array -> Boolean + == self that = + if False then True that else + eq_at i = self.at i == that.at i + eq_at 0 + """); } @Test public void testNestedBlocks() { parseTest( """ - type Array - meaning = - catch_primitive handler - 42 - """); + type Array + meaning = + catch_primitive handler + 42 + """); } @Test public void testSelf1() { - parseTest(""" - contains self elem = self.contains Nothing - """); + parseTest( + """ + contains self elem = self.contains Nothing + """); } @Test public void testPanic_184119084() { - parseTest(""" - type Foo - type Bar + parseTest( + """ + type Foo + type Bar - main = 42 - """); + main = 42 + """); } @Test public void testMetadataRaw() { parseTest( """ - main = - foo = 42 + main = + foo = 42 - #### METADATA #### - [[{"index": {"value": 17}, "size": {"value": 2}}, "0270bcdf-26b8-4b99-8745-85b3600c7359"]] - [] - """); + #### METADATA #### + [[{"index": {"value": 17}, "size": {"value": 2}}, "0270bcdf-26b8-4b99-8745-85b3600c7359"]] + [] + """); } @Test public void testDocumentationComment() { - parseTest(""" - ## A type representing computations that may fail. - type Maybe - """); + parseTest( + """ + ## A type representing computations that may fail. + type Maybe + """); } @Test public void testColumnSelector() { parseTest( """ - ## Specifies a selection of columns from the table on which an operation is - going to be performed. - type Column_Selector - By_Index (indexes : Vector Integer) - By_Column (columns : Vector Column) - """); + ## Specifies a selection of columns from the table on which an operation is + going to be performed. + type Column_Selector + By_Index (indexes : Vector Integer) + By_Column (columns : Vector Column) + """); } @Test public void testAssignments() { parseTest( """ - from_java_set java_set = - owner = Builder.new - group = Builder.new - others = Builder.new + from_java_set java_set = + owner = Builder.new + group = Builder.new + others = Builder.new """); } @@ -443,21 +489,21 @@ public void testAssignments() { public void testNumberTimes() { parseTest( """ - Standard.Base.Number.times : List Any - Standard.Base.Number.times self act = - act - """); + Standard.Base.Number.times : List Any + Standard.Base.Number.times self act = + act + """); } @Test public void testIfThenBlock() { parseTest( """ - from_java_set java_set = - if java_set.contains PosixFilePermission.OWNER_READ then - owner.append Read - if java_set.contains PosixFilePermission.OWNER_WRITE then - owner.append Write + from_java_set java_set = + if java_set.contains PosixFilePermission.OWNER_READ then + owner.append Read + if java_set.contains PosixFilePermission.OWNER_WRITE then + owner.append Write """); } @@ -465,8 +511,8 @@ public void testIfThenBlock() { public void testInvokeFilePermissions() { parseTest( """ - from_java_set java_set = - File_Permissions owner.to_vector group.to_vector others.to_vector + from_java_set java_set = + File_Permissions owner.to_vector group.to_vector others.to_vector """); } @@ -522,79 +568,83 @@ public void testExportFromAllHiding() { @Test public void testTextLiteral() { - parseTest(""" - main = "I'm an inline raw text!" - """); + parseTest( + """ + main = "I'm an inline raw text!" + """); } @Test public void testTextLiteralWithEscape() { parseTest( """ - wrap_junit_testsuites = '\\n' - """); + wrap_junit_testsuites = '\\n' + """); } @Test public void testRawBlockLiteral() { // mimics TextTest - parseTest(""" - x = \"\"\" - Foo - Bar - Baz - """); + parseTest( + """ + x = \"\"\" + Foo + Bar + Baz + """); } @Test public void testVariousKindsOfUnicodeWhitespace() { - parseTest(""" - t = '\\v\\f\\u{200a}\\u{202f}\\u{205F}\\u{3000}'.trim - """); + parseTest( + """ + t = '\\v\\f\\u{200a}\\u{202f}\\u{205F}\\u{3000}'.trim + """); } @Test public void testLambda() { - parseTest(""" - f = map _->alphabet - """); + parseTest( + """ + f = map _->alphabet + """); } @Test public void testMultiParameterFunction() { parseTest( """ - from Standard.Base import all - import Standard.Base.System + from Standard.Base import all + import Standard.Base.System - measure : Any -> Text -> Integer -> Integer -> Nothing - measure = ~act -> label -> iter_size -> num_iters -> - 42 - """); + measure : Any -> Text -> Integer -> Integer -> Nothing + measure = ~act -> label -> iter_size -> num_iters -> + 42 + """); } @Test public void testTestGroup() { parseTest( """ - type Test - ## Creates a new test group, describing properties of the object - described by `self`. + type Test + ## Creates a new test group, describing properties of the object + described by `self`. - Arguments: - - name: The name of the test group. - - behaviors: An action containing a set of specs for the group. - - pending: A reason for why the test is pending, or `Nothing` when it is not - pending. + Arguments: + - name: The name of the test group. + - behaviors: An action containing a set of specs for the group. + - pending: A reason for why the test is pending, or `Nothing` when it is not + pending. - > Example - Adding a test group. + > Example + Adding a test group. - from Standard.Test import Test, Test_Suite + from Standard.Test import Test, Test_Suite - example_group = Test_Suite.run <| - Test.group "Number" <| Nothing - group : Text -> Any -> (Text | Nothing) -> Nothing + example_group = Test_Suite.run <| + Test.group "Number" <| Nothing + group : Text -> Any -> (Text | Nothing) -> Nothing """); } @@ -602,131 +652,138 @@ public void testTestGroup() { public void testEmptyGroup() { parseTest( """ - main = - x = Panic.catch Any () .convert_to_dataflow_error - x.catch_primitive err-> - case err of - Syntax_Error_Data msg -> "Oopsie, it's a syntax error: " + msg - """); + main = + x = Panic.catch Any () .convert_to_dataflow_error + x.catch_primitive err-> + case err of + Syntax_Error_Data msg -> "Oopsie, it's a syntax error: " + msg + """); } @Test public void testEmptyGroup2() { - parseTest(""" - main = - x = () - x = 5 - """); + parseTest( + """ + main = + x = () + x = 5 + """); } @Test public void testTestGroupSimple() { parseTest( """ - group1 : Text -> Any -> (Text | Nothing) -> Nothing + group1 : Text -> Any -> (Text | Nothing) -> Nothing - type Test - group2 : Text -> Any -> (Text | Nothing) -> Nothing - """); + type Test + group2 : Text -> Any -> (Text | Nothing) -> Nothing + """); } @Test public void testWildcardLeftHandSide() { parseTest( """ - Any.should_succeed self frames_to_skip=0 = - _ = frames_to_skip + Any.should_succeed self frames_to_skip=0 = + _ = frames_to_skip """); } @Test public void testReverseListType() { - parseTest(""" - reverse_list : List Any -> List - reverse_list list = List.Nil - """); + parseTest( + """ + reverse_list : List Any -> List + reverse_list list = List.Nil + """); } @Test public void testReverseList() { parseTest( """ - reverse_list list = - go = list -> acc -> case list of - List.Cons h t -> go t (List.Cons h acc) - List.Cons h _ -> acc - ListNil -> acc - _ -> acc - res = go list List.Nil - res - """); + reverse_list list = + go = list -> acc -> case list of + List.Cons h t -> go t (List.Cons h acc) + List.Cons h _ -> acc + ListNil -> acc + _ -> acc + res = go list List.Nil + res + """); } @Test public void testProblemHandling() { parseTest( """ - test_problem_handling : (Problem_Behavior -> Any) -> Vector Any -> (Any -> Nothing) -> Nothing - test_problem_handling action expected_problems result_checker = - result_checker result_ignoring - """); + test_problem_handling : (Problem_Behavior -> Any) -> Vector Any -> (Any -> Nothing) -> Nothing + test_problem_handling action expected_problems result_checker = + result_checker result_ignoring + """); } @Test public void testProblemHandling2() { parseTest( """ - test_problem_handling action expected_problems result_checker = - error_result . should_fail_with first_problem_type frames_to_skip=3 - warnings_checker warnings = - ## TODO [RW] we are not checking if there are no duplicate warnings, because the warnings are in fact duplicated - we should figure out how to handle that and then possibly modify the test - warnings . should_contain_the_same_elements_as expected_problems frames_to_skip=3 - """); + test_problem_handling action expected_problems result_checker = + error_result . should_fail_with first_problem_type frames_to_skip=3 + warnings_checker warnings = + ## TODO [RW] we are not checking if there are no duplicate warnings, because the warnings are in fact duplicated - we should figure out how to handle that and then possibly modify the test + warnings . should_contain_the_same_elements_as expected_problems frames_to_skip=3 + """); } @Test public void testNamedArgument() { - parseTest(""" - fn = get_all frames_to_skip=1 - """); + parseTest( + """ + fn = get_all frames_to_skip=1 + """); } @Test public void testVectorLiteralEmpty() { - parseTest(""" - fn = [] - """); + parseTest( + """ + fn = [] + """); } @Test public void testVectorLiteralOne() { - parseTest(""" - fn = [ 1 ] - """); + parseTest( + """ + fn = [ 1 ] + """); } @Test public void testVectorLiteralMany() { - parseTest(""" - fn = [ 1, 2, 3 ] - """); + parseTest( + """ + fn = [ 1, 2, 3 ] + """); } @Test public void testInvokeMethod() { - parseTest(""" - fn = result_ignoring . should_equal - """); + parseTest( + """ + fn = result_ignoring . should_equal + """); } @Test public void testTableDataArgumentInCase() { parseTest( """ - process_to_json_text value = - json = case value of - Table.Table_Data _ -> json_from_table value - _ -> value.to_json + process_to_json_text value = + json = case value of + Table.Table_Data _ -> json_from_table value + _ -> value.to_json """); } @@ -734,14 +791,14 @@ public void testTableDataArgumentInCase() { public void testVisualizationCaseOf() { parseTest( """ - prepare_visualization : Any -> Integer -> Json - prepare_visualization x max_rows=1000 = case x of - Array -> - prepare_visualization (Vector.from_polyglot_array x) max_rows - - # Anything else will be visualized with the JSON or matrix visualization - _ -> - Json.from_pairs [["json", x]] . to_text + prepare_visualization : Any -> Integer -> Json + prepare_visualization x max_rows=1000 = case x of + Array -> + prepare_visualization (Vector.from_polyglot_array x) max_rows + + # Anything else will be visualized with the JSON or matrix visualization + _ -> + Json.from_pairs [["json", x]] . to_text """); } @@ -749,168 +806,182 @@ public void testVisualizationCaseOf() { public void testAggregateColumnGroupByTrue() { parseTest( """ - prepare_aggregate_columns : [Aggregate_Column] -> Table -> Problem_Behavior -> Resolved_Aggregate_Columns - prepare_aggregate_columns aggregates table = - # Grouping Key - is_a_key c = case c of - Aggregate_Column.Group_By _ _ -> True - _ -> False - """); + prepare_aggregate_columns : [Aggregate_Column] -> Table -> Problem_Behavior -> Resolved_Aggregate_Columns + prepare_aggregate_columns aggregates table = + # Grouping Key + is_a_key c = case c of + Aggregate_Column.Group_By _ _ -> True + _ -> False + """); } @Test public void testUnaryDot() { - parseTest(""" - write_file = ExcelWriter.setEnsoToTextCallbackIfUnset (.to_text) - """); + parseTest( + """ + write_file = ExcelWriter.setEnsoToTextCallbackIfUnset (.to_text) + """); } @Test public void testUnaryMinus() { - parseTest(""" - meaning = -42 - """); + parseTest( + """ + meaning = -42 + """); } @Test public void testExtensionMethod() { - parseTest(""" - Any.meaning = -42 - """); + parseTest( + """ + Any.meaning = -42 + """); } @Test public void testExtensionOperator() { - parseTest(""" - Text.* : Integer -> Text - Text.* self = 42 - """); + parseTest( + """ + Text.* : Integer -> Text + Text.* self = 42 + """); } @Test public void testTypeSignature() { parseTest( """ - resolve_aggregate table problem_builder aggregate_column = - table_columns = table.columns + resolve_aggregate table problem_builder aggregate_column = + table_columns = table.columns - resolve : (Integer|Text|Column) -> Column ! Internal_Missing_Column_Error - resolve c = 42 - """); + resolve : (Integer|Text|Column) -> Column ! Internal_Missing_Column_Error + resolve c = 42 + """); } @Test public void testTypeSignature2() { - parseTest(""" - type Baz - resolve : Integer -> Column - """); + parseTest( + """ + type Baz + resolve : Integer -> Column + """); } @Test public void testTypeSignatureQualified() { - parseTest(""" - type Baz - Foo.resolve : Integer -> Column - """); + parseTest( + """ + type Baz + Foo.resolve : Integer -> Column + """); } @Test public void testMethodDef() { - parseTest(""" - type Foo - id x = x - """); + parseTest( + """ + type Foo + id x = x + """); } @Test public void testSelfTypeKeyword() { parseTest( """ - type My_Type - Cons_A x - Cons_B y=(Self.Cons_A 10) + type My_Type + Cons_A x + Cons_B y=(Self.Cons_A 10) - static = 123 + static = 123 - static_use = Self.static + (Self.Cons_A 5).x - instance_use self = Self.static + self.x + (Self.Cons_A 5).x + static_use = Self.static + (Self.Cons_A 5).x + instance_use self = Self.static + self.x + (Self.Cons_A 5).x - static_match x = case x of - Self -> "it matched" - _ -> "it didn't match" + static_match x = case x of + Self -> "it matched" + _ -> "it didn't match" - matching_method self = case self of - Self.Cons_A y -> y + 2 + matching_method self = case self of + Self.Cons_A y -> y + 2 - match_by_type x = case x of - _ : Self -> "it's a Self" - _ -> "it's a something else" - """); + match_by_type x = case x of + _ : Self -> "it's a Self" + _ -> "it's a something else" + """); } @Test public void testCaseOnTextLiteral() { - parseTest(""" - choose ch = case ch of - "yes" -> True - "no" -> False - """); + parseTest( + """ + choose ch = case ch of + "yes" -> True + "no" -> False + """); } @Test public void testCaseWithUnderscore() { - parseTest(""" - choose ch = case ch of - 0 -> _.name - _ -> Nothing - """); + parseTest( + """ + choose ch = case ch of + 0 -> _.name + _ -> Nothing + """); } @Test public void testCaseWithLowerCaseA() { - parseTest(""" - map_nothing self = case self of - a -> f a - """); + parseTest( + """ + map_nothing self = case self of + a -> f a + """); } @Test public void testBalanceUpperCase() { - parseTest(""" - balance_left k x l r = case r of - Bin _ lk lx Tip -> 42 - """); + parseTest( + """ + balance_left k x l r = case r of + Bin _ lk lx Tip -> 42 + """); } @Test public void testBalanceLowerCase() { - parseTest(""" - balance_left k x l r = case r of - Bin _ lk lx tip -> 42 - """); + parseTest( + """ + balance_left k x l r = case r of + Bin _ lk lx tip -> 42 + """); } @Test public void testVectorVectorSimple() { - parseTest(""" - type Vector - build : Matrix Any Float - """); + parseTest( + """ + type Vector + build : Matrix Any Float + """); } @Test public void testVectorVectorAny() { parseTest( """ - type Vector - build : Standard.Base.Vector.Matrix Standard.Base.Any Standard.Base.Float - """); + type Vector + build : Standard.Base.Vector.Matrix Standard.Base.Any Standard.Base.Float + """); } @Test public void testCaseOfVector() { - parseTest(""" + parseTest( + """ m other = case other of _:Vector.Vector -> 0 """); @@ -920,198 +991,215 @@ public void testCaseOfVector() { public void testOperatorSectionRight() { parseTest( """ - type Filter_Condition - to_predicate self = case self of - Less value -> (~ifT) -> ~ifF -> if c == 0 then ifT else ifF - """); + parseTest( + """ + ifTest = c -> (~ifT) -> ~ifF -> if c == 0 then ifT else ifF + """); } @Test public void testTextArrayType() { - parseTest(""" - type Connection - table_types : [Text] - """); + parseTest( + """ + type Connection + table_types : [Text] + """); } @Test public void testListBody() { parseTest( """ - list directory name_filter=Nothing recursive=False = - new directory . list name_filter=name_filter recursive=recursive - """); + list directory name_filter=Nothing recursive=False = + new directory . list name_filter=name_filter recursive=recursive + """); } @Test public void testLambdaBody() { - parseTest(""" - list = - all_files.filter file-> - all_files - """); + parseTest( + """ + list = + all_files.filter file-> + all_files + """); } @Test public void testCaseWithComment() { parseTest( """ - ansi_bold : Boolean -> Text -> Text - ansi_bold enabled txt = - case Platform.os of - ## Output formatting for Windows is not currently supported. - Platform.OS.Windows -> txt - _ -> if enabled then Nothing - """); + ansi_bold : Boolean -> Text -> Text + ansi_bold enabled txt = + case Platform.os of + ## Output formatting for Windows is not currently supported. + Platform.OS.Windows -> txt + _ -> if enabled then Nothing + """); } @Test public void testAlternationTypes() { - parseTest(""" - foo : [Integer | Text] -> (Integer | Text) - foo v = v.at 0 - """); + parseTest( + """ + foo : [Integer | Text] -> (Integer | Text) + foo v = v.at 0 + """); } @Test public void testGroupOfPatterns() { parseTest( """ - sum self = case self of - Group (A _) (B _ _) (C _ e _) (D _ f _ g) -> e + f + g - """); + sum self = case self of + Group (A _) (B _ _) (C _ e _) (D _ f _ g) -> e + f + g + """); } @Test public void testNameAsMethodApp() { - parseTest(""" - f = foo x=A.B - """); + parseTest( + """ + f = foo x=A.B + """); } @Test public void testIsMethodWithSpaces() { - parseTest(""" - f = 0.up_to . all f - """); + parseTest( + """ + f = 0.up_to . all f + """); } @Test public void testIsMethodWithoutSpaces() { - parseTest(""" - f = 0.up_to.all f - """); + parseTest( + """ + f = 0.up_to.all f + """); } @Test public void testHandleRequestError() { - parseTest(""" - request self req = - handle_request_error = - 42 - """); + parseTest( + """ + request self req = + handle_request_error = + 42 + """); } @Test public void testWriteFlag() { - parseTest(""" - type Write_Flag - JPEG_Quality val:Integer=95 - """); + parseTest( + """ + type Write_Flag + JPEG_Quality val:Integer=95 + """); } @Test public void testHasDefaultsSuspended() { - parseTest(""" - Atom.constructor self = get_atom_constructor self.value ... - """); + parseTest( + """ + Atom.constructor self = get_atom_constructor self.value ... + """); } @Test public void testVectorVector() { - parseTest(""" - get_stack_trace : Vector.Vector Stack_Trace_Element - """); + parseTest( + """ + get_stack_trace : Vector.Vector Stack_Trace_Element + """); } @Test public void testSidesPlus() { - parseTest(""" - result = reduce (+) - """); + parseTest( + """ + result = reduce (+) + """); } @Test public void testConstructorMultipleNamedArgs1() { parseTest( """ - x = Regex_Matcher.Regex_Matcher_Data case_sensitivity=Case_Sensitivity.Sensitive dot_matches_newline=True - """); + x = Regex_Matcher.Regex_Matcher_Data case_sensitivity=Case_Sensitivity.Sensitive dot_matches_newline=True + """); } @Test public void testDocAtEndOfBlock() { - parseTest(""" - x = - 23 - ## end of block - """); + parseTest( + """ + x = + 23 + ## end of block + """); } @Test public void testMethodSections() { - parseTest(""" - x = .from self=Foo - """); + parseTest( + """ + x = .from self=Foo + """); } @Test public void testGroupArgument() { - parseTest(""" - foo = x -> (y = bar x) -> x + y - """); + parseTest( + """ + foo = x -> (y = bar x) -> x + y + """); } @Test public void testRuntimeServerTestCode() { parseTest( """ - from Standard.Base.Data.Numbers import Number - - main = - x = 6 - y = x.foo 5 - z = y + 5 - z - - Number.foo self = x -> - y = self + 3 - z = y * x - z - """, + from Standard.Base.Data.Numbers import Number + + main = + x = 6 + y = x.foo 5 + z = y + 5 + z + + Number.foo self = x -> + y = self + 3 + z = y * x + z + """, true, true, true); @@ -1119,47 +1207,49 @@ public void testRuntimeServerTestCode() { @Test public void testResolveExecutionContext() { - parseTest(""" - foo : A -> B -> C in Input - """); + parseTest( + """ + foo : A -> B -> C in Input + """); } @Test public void testSugaredFunctionDefinition() { - parseTest(""" - main = - f a b = a - b - f 10 20 - """); + parseTest( + """ + main = + f a b = a - b + f 10 20 + """); } @Test public void testAtomBenchmarks1() { parseTest( """ - import Standard.Base.Data.List.List + import Standard.Base.Data.List.List - main = - generator fn acc i end = if i == end then acc else @Tail_Call generator fn (fn acc i) i+1 end - res = generator (acc -> x -> List.Cons x acc) List.Nil 1 1000000 - res - """); + main = + generator fn acc i end = if i == end then acc else @Tail_Call generator fn (fn acc i) i+1 end + res = generator (acc -> x -> List.Cons x acc) List.Nil 1 1000000 + res + """); } @Test public void testAtomBenchmarks3() { parseTest( """ - import Standard.Base.Data.List.List + import Standard.Base.Data.List.List - List.mapReverse self f acc = case self of - List.Cons h t -> @Tail_Call t.mapReverse f (List.Cons (f h) acc) - _ -> acc + List.mapReverse self f acc = case self of + List.Cons h t -> @Tail_Call t.mapReverse f (List.Cons (f h) acc) + _ -> acc - main = list -> - res = list.mapReverse (x -> x + 1) List.Nil - res - """, + main = list -> + res = list.mapReverse (x -> x + 1) List.Nil + res + """, true, true, false); @@ -1169,19 +1259,19 @@ public void testAtomBenchmarks3() { public void testShouldQuoteValuesContainingTheCommentSymbol() { parseTest( """ - suite = - Test.specify "should quote values containing the comment symbol if comments are enabled" <| - format = Delimited_Format.Delimited ',' . with_comments - table.write file format on_problems=..Report_Error . should_succeed - expected_text_2 = normalize_lines <| \""" - "#",B - b, - x,"#" - "#",abc - text_2 = File.read_text file - text_2.should_equal expected_text_2 - file.delete - """, + suite = + Test.specify "should quote values containing the comment symbol if comments are enabled" <| + format = Delimited_Format.Delimited ',' . with_comments + table.write file format on_problems=..Report_Error . should_succeed + expected_text_2 = normalize_lines <| \""" + "#",B + b, + x,"#" + "#",abc + text_2 = File.read_text file + text_2.should_equal expected_text_2 + file.delete + """, true, true, false); @@ -1191,12 +1281,12 @@ public void testShouldQuoteValuesContainingTheCommentSymbol() { public void testEmptyValueBetweenComments() { parseTest( """ - expected_text = normalize_lines <| \""" - A,B - 1, - ,"" - 3,abc - """, + expected_text = normalize_lines <| \""" + A,B + 1, + ,"" + 3,abc + """, true, true, false); @@ -1206,9 +1296,9 @@ public void testEmptyValueBetweenComments() { public void testQuotedValues() { parseTest( """ - expected_text = normalize_lines <| \""" - "one, two, three",-1.5,42,"4\"000", - """, + expected_text = normalize_lines <| \""" + "one, two, three",-1.5,42,"4\"000", + """, true, true, false); @@ -1218,26 +1308,26 @@ public void testQuotedValues() { public void testSimpleTripleQuote() { parseTest( """ - expected_response = Json.parse <| ''' - { - "headers": { - "Content-Length": "13", - "Content-Type": "application/json", - "User-Agent": "Java-http-client/11.0.13" - }, - "origin": "127.0.0.1", - "url": "", - "args": {}, - "data": "{\\"key\\":\\"val\\"}", - "files": null, - "form": null, - "json": { - "key": "val" - } - } - json = Json.parse <| ''' - {"key":"val"} - res = Http.new.post_json url_post json + expected_response = Json.parse <| ''' + { + "headers": { + "Content-Length": "13", + "Content-Type": "application/json", + "User-Agent": "Java-http-client/11.0.13" + }, + "origin": "127.0.0.1", + "url": "", + "args": {}, + "data": "{\\"key\\":\\"val\\"}", + "files": null, + "form": null, + "json": { + "key": "val" + } + } + json = Json.parse <| ''' + {"key":"val"} + res = Http.new.post_json url_post json """, true, true, @@ -1248,29 +1338,31 @@ public void testSimpleTripleQuote() { public void testInThePresenceOfComments() { parseTest( """ - # this is a comment - #this too - ## But this is a doc. - main = # define main - y = 1 # assign one to `y` - x = 2 # assign two to #x - # perform the addition - x + y # the addition is performed here - """); + # this is a comment + #this too + ## But this is a doc. + main = # define main + y = 1 # assign one to `y` + x = 2 # assign two to #x + # perform the addition + x + y # the addition is performed here + """); } @Test public void testNPE183892665() { - parseTest(""" - foo : Integer -> - """); + parseTest( + """ + foo : Integer -> + """); } @Test public void testNamedDefaultedArguments183953473() { - parseTest(""" - main = @Tail_Call summator (current = 0) (acc = 1) - """); + parseTest( + """ + main = @Tail_Call summator (current = 0) (acc = 1) + """); } @Test @@ -1308,66 +1400,66 @@ public void testSkip() throws IOException { public void testBlockSyntax() throws IOException { equivalenceTest( """ - nums v fm ff n = v . map fm . filter ff . take n - """, + nums v fm ff n = v . map fm . filter ff . take n + """, """ - nums v fm ff n = v - . map fm - . filter ff - . take n - """); + nums v fm ff n = v + . map fm + . filter ff + . take n + """); } @Test public void testBlockSyntaxOperators() throws IOException { equivalenceTest( """ - value = nums * each random + constant - """, + value = nums * each random + constant + """, """ - value = nums - * each random - + constant - """); + value = nums + * each random + + constant + """); } @Test public void testBlockSyntaxOperators2() throws IOException { equivalenceTest( """ - value = (nums + each random) * constant - """, + value = (nums + each random) * constant + """, """ - value = nums - + each random - * constant - """); + value = nums + + each random + * constant + """); } @Test public void testBlockSyntaxOperators3() throws IOException { equivalenceTest( """ - v = (rect1 . width) . center - """, + v = (rect1 . width) . center + """, """ - v = rect1 - . width - . center - """); + v = rect1 + . width + . center + """); } @Test public void testBlockSyntaxOperators4() throws IOException { equivalenceTest( """ - v = (rect1 . width 4) . center 3 2 - """, + v = (rect1 . width 4) . center 3 2 + """, """ - v = rect1 - . width 4 - . center 3 2 - """); + v = rect1 + . width 4 + . center 3 2 + """); } @Test @@ -1376,14 +1468,14 @@ public void testPrivateModules() throws IOException { List.of( "private", """ - # Comment - private - """, + # Comment + private + """, """ - # Comment with empty line + # Comment with empty line - private - """); + private + """); for (var moduleCode : moduleCodes) { parseTest(moduleCode); var module = compile("private"); @@ -1395,7 +1487,8 @@ public void testPrivateModules() throws IOException { @Test public void testPrivateMethodInType() { - String code = """ + String code = + """ type My_Type private method self = self """; @@ -1415,7 +1508,8 @@ public void testPrivateMethodInType() { @Test public void testPrivateTopLevelMethod() throws IOException { - String code = """ + String code = + """ private method x = x """; var ir = compile(code); @@ -1429,7 +1523,8 @@ public void testPrivateTopLevelMethod() throws IOException { @Test public void testPrivateAndPublicTopScopeMethods() { - var code = """ + var code = + """ private priv_method x = x pub_method x = x """; @@ -1460,44 +1555,46 @@ public void testPrivateAndPublicTopScopeMethods() { public void testPrivateConstructor() { parseTest( """ - type My_Type - private Ctor_1 a b - private Ctor_2 c d - """); + type My_Type + private Ctor_1 a b + private Ctor_2 c d + """); // Mixing public and private constructor is a semantic error, not a syntax error. // So parsing should be fine. parseTest( """ - type My_Type - private Ctor_1 a b - Ctor_2 c d - """); + type My_Type + private Ctor_1 a b + Ctor_2 c d + """); } @Test public void ise_184219679() { parseTest( """ - from Standard.Base import all + from Standard.Base import all - main = - x = 42 - y = if x == 42 then 10 else - 20 - IO.println y - """); + main = + x = 42 + y = if x == 42 then 10 else + 20 + IO.println y + """); } @Test public void testEmptyBody() { - parseTest(""" - main = - """); + parseTest( + """ + main = + """); } @Test public void testAnnotatedExpression() { - String code = """ + String code = + """ type A main = 42 : A """; @@ -1517,7 +1614,8 @@ public void testAnnotatedExpression() { @Test public void testSugaredTypeBodyHasLocation() { - var code = """ + var code = + """ type My_Type f self = self """; diff --git a/engine/runtime-test-instruments/src/main/java/org/enso/interpreter/test/instruments/tck/EnsoTckLanguageProvider.java b/engine/runtime-test-instruments/src/main/java/org/enso/interpreter/test/instruments/tck/EnsoTckLanguageProvider.java index 3c7a9bd26403..85e98d714e41 100644 --- a/engine/runtime-test-instruments/src/main/java/org/enso/interpreter/test/instruments/tck/EnsoTckLanguageProvider.java +++ b/engine/runtime-test-instruments/src/main/java/org/enso/interpreter/test/instruments/tck/EnsoTckLanguageProvider.java @@ -19,9 +19,14 @@ public String getId() { @Override public Value createIdentityFunction(Context context) { - var id = context.eval("enso", """ - id a = a - """).invokeMember("eval_expression", "id"); + var id = + context + .eval( + "enso", + """ + id a = a + """) + .invokeMember("eval_expression", "id"); return id; } @@ -34,9 +39,11 @@ public Collection createValueConstructors(Context context) { public Collection createExpressions(Context context) { var plus = context - .eval("enso", """ - plus a b = a + b - """) + .eval( + "enso", + """ + plus a b = a + b + """) .invokeMember("eval_expression", "plus"); return List.of( @@ -54,9 +61,11 @@ public Collection createExpressions(Context context) { public Collection createStatements(Context context) { var when = context - .eval("enso", """ - when c = if c then 1 else -1 - """) + .eval( + "enso", + """ + when c = if c then 1 else -1 + """) .invokeMember("eval_expression", "when"); ; var which = @@ -64,12 +73,12 @@ public Collection createStatements(Context context) { .eval( "enso", """ - which c = case c of - 0 -> "zero" - 1 -> "one" - 2 -> "two" - _ -> "a lot" - """) + which c = case c of + 0 -> "zero" + 1 -> "one" + 2 -> "two" + _ -> "a lot" + """) .invokeMember("eval_expression", "which"); return List.of( Snippet.newBuilder("if", when, TypeDescriptor.NUMBER) @@ -88,9 +97,12 @@ public Collection createScripts(Context context) { @Override public Collection createInvalidSyntaxScripts(Context context) { return List.of( - Source.newBuilder("enso", """ - main = x + 2 - """, "unknown_x.enso") + Source.newBuilder( + "enso", + """ + main = x + 2 + """, + "unknown_x.enso") .buildLiteral()); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/EqualsBuiltinNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/EqualsBuiltinNode.java index 2f4789ad5882..b66d67665505 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/EqualsBuiltinNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/EqualsBuiltinNode.java @@ -12,18 +12,18 @@ name = "==", description = """ - Compares self with other object and returns True iff `self` is exactly the same as - the other object, including all its transitively accessible properties or fields, - False otherwise. + Compares self with other object and returns True iff `self` is exactly the same as + the other object, including all its transitively accessible properties or fields, + False otherwise. - Can handle arbitrary objects, including all foreign objects. + Can handle arbitrary objects, including all foreign objects. - Does not throw dataflow errors or panics. + Does not throw dataflow errors or panics. - Note that this is different than `Meta.is_same_object`, which checks whether two - references point to the same object on the heap. Moreover, `Meta.is_same_object` - implies `Any.==` for all object with the exception of `Number.nan`. - """) + Note that this is different than `Meta.is_same_object`, which checks whether two + references point to the same object on the heap. Moreover, `Meta.is_same_object` + implies `Any.==` for all object with the exception of `Number.nan`. + """) public final class EqualsBuiltinNode extends Node { @Child private EqualsNode node; @Child private AppendWarningNode append; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/IntegerNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/IntegerNode.java index af4fb17cfac0..8a2a28f7c2d9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/IntegerNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/IntegerNode.java @@ -12,11 +12,13 @@ import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.number.EnsoBigInteger; -/** A base class for nodes that operate on Enso Integers (e.g. either {@code long} or {@link EnsoBigInteger}). Contains helper - * methods that can be used from subclasses of either {@link Unary} or {@link Binary} - * variant of this class. +/** + * A base class for nodes that operate on Enso Integers (e.g. either {@code long} or {@link + * EnsoBigInteger}). Contains helper methods that can be used from subclasses of either {@link + * Unary} or {@link Binary} variant of this class. */ -public sealed abstract class IntegerNode extends Node permits IntegerNode.Unary, IntegerNode.Binary { +public abstract sealed class IntegerNode extends Node + permits IntegerNode.Unary, IntegerNode.Binary { @Child private ToEnsoNumberNode toEnsoNumberNode; @Child private InteropLibrary iop; @@ -86,13 +88,14 @@ final ToEnsoNumberNode toEnsoNumberNode() { } /** - * Node operating on a single Enso Integer (e.g. either {@code long} or {@link EnsoBigInteger}) argument. + * Node operating on a single Enso Integer (e.g. either {@code long} or {@link EnsoBigInteger}) + * argument. */ - public non-sealed abstract static class Unary extends IntegerNode { + public abstract static non-sealed class Unary extends IntegerNode { public final Object execute(Object own) { var ensoSelf = toEnsoNumberOrNull(own, false); if (ensoSelf == null) { - throw throwTypeErrorIfNotInt(own); + throw throwTypeErrorIfNotInt(own); } return executeUnary(ensoSelf); } @@ -101,14 +104,15 @@ public final Object execute(Object own) { } /** - * Node operating on a tow Enso Integers (e.g. either {@code long} or {@link EnsoBigInteger}) arguments. + * Node operating on a tow Enso Integers (e.g. either {@code long} or {@link EnsoBigInteger}) + * arguments. */ - public non-sealed abstract static class Binary extends IntegerNode { + public abstract static non-sealed class Binary extends IntegerNode { public final Object execute(Object own, Object that) { var ensoSelf = toEnsoNumberOrNull(own, false); var ensoThat = toEnsoNumberOrNull(that); if (ensoSelf == null || ensoThat == null) { - throw throwTypeErrorIfNotInt(own, that); + throw throwTypeErrorIfNotInt(own, that); } return executeBinary(ensoSelf, ensoThat); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/ParseIntegerNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/ParseIntegerNode.java index ff0c5ccca852..e3164f151b63 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/ParseIntegerNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/integer/ParseIntegerNode.java @@ -14,8 +14,10 @@ @BuiltinMethod( type = "Integer", name = "parse", - description = """ -Parse integer number""", + description = +""" +Parse integer number\ +""", autoRegister = false) public final class ParseIntegerNode extends Node { @Child ToJavaStringNode toJavaString = ToJavaStringNode.build(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/typecheck/SingleTypeCheckNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/typecheck/SingleTypeCheckNode.java index e1272b331d8c..cad45f2257af 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/typecheck/SingleTypeCheckNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/typecheck/SingleTypeCheckNode.java @@ -1,8 +1,16 @@ package org.enso.interpreter.node.typecheck; - +import com.oracle.truffle.api.CompilerAsserts; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.frame.MaterializedFrame; +import com.oracle.truffle.api.frame.VirtualFrame; +import com.oracle.truffle.api.nodes.ExplodeLoop; +import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.EnsoLanguage; import org.enso.interpreter.node.EnsoRootNode; +import org.enso.interpreter.node.callable.dispatch.InvokeFunctionNode; import org.enso.interpreter.node.expression.builtin.meta.IsValueOfTypeNode; import org.enso.interpreter.runtime.EnsoContext; import org.enso.interpreter.runtime.callable.UnresolvedConstructor; @@ -15,17 +23,7 @@ import org.enso.interpreter.runtime.library.dispatch.TypeOfNode; import org.graalvm.collections.Pair; -import com.oracle.truffle.api.CompilerAsserts; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; -import com.oracle.truffle.api.frame.MaterializedFrame; -import com.oracle.truffle.api.frame.VirtualFrame; -import com.oracle.truffle.api.nodes.ExplodeLoop; -import com.oracle.truffle.api.nodes.Node; -import org.enso.interpreter.node.callable.dispatch.InvokeFunctionNode; - -non-sealed abstract class SingleTypeCheckNode extends AbstractTypeCheckNode { +abstract non-sealed class SingleTypeCheckNode extends AbstractTypeCheckNode { private final Type expectedType; @Node.Child IsValueOfTypeNode checkType; @CompilerDirectives.CompilationFinal private String expectedTypeMessage; @@ -68,17 +66,14 @@ Object doWithConversionCached( @Specialization(replaces = "doWithConversionCached") Object doWithConversionUncached( - VirtualFrame frame, - Object v, - @Cached.Shared("typeOfNode") @Cached TypeOfNode typeOfNode) { + VirtualFrame frame, Object v, @Cached.Shared("typeOfNode") @Cached TypeOfNode typeOfNode) { var type = findType(typeOfNode, v); - return doWithConversionUncachedBoundary( - frame == null ? null : frame.materialize(), v, type); + return doWithConversionUncachedBoundary(frame == null ? null : frame.materialize(), v, type); } @Override final Object findDirectMatch(VirtualFrame frame, Object v) { - return directMatchImpl(v); + return directMatchImpl(v); } @ExplodeLoop @@ -93,7 +88,8 @@ private final Object directMatchImpl(Object v) { var lazyCheckFn = lazyCheck.wrapThunk(fn); return lazyCheckFn; } - assert EnsoContext.get(this).getBuiltins().any() != expectedType : "Don't check for Any: " + expectedType; + assert EnsoContext.get(this).getBuiltins().any() != expectedType + : "Don't check for Any: " + expectedType; if (v instanceof EnsoMultiValue mv) { if (castTo == null) { CompilerDirectives.transferToInterpreter(); @@ -140,7 +136,7 @@ private TypeToConvertNode(Function conv, Type intoType) { final Object executeConvert(VirtualFrame frame, Object value) { var ctx = EnsoContext.get(this); var state = ctx.currentState(); - return invokeNode.execute(conv, frame, state, new Object[] { intoType, value }); + return invokeNode.execute(conv, frame, state, new Object[] {intoType, value}); } } @@ -165,7 +161,8 @@ final Type[] findType(TypeOfNode typeOfNode, Object v) { return findType(typeOfNode, v, null); } - final Type[] findType(TypeOfNode typeOfNode, Object v, Type[] previous) {; + final Type[] findType(TypeOfNode typeOfNode, Object v, Type[] previous) { + ; if (v instanceof EnsoMultiValue multi) { var all = typeOfNode.findAllTypesOrNull(multi, false); return all; @@ -194,8 +191,7 @@ private Object handleWithConversion(VirtualFrame frame, Object v, TypeToConvertN } @CompilerDirectives.TruffleBoundary - private Object doWithConversionUncachedBoundary( - MaterializedFrame frame, Object v, Type[] type) { + private Object doWithConversionUncachedBoundary(MaterializedFrame frame, Object v, Type[] type) { var c = findConversionNode(type); return handleWithConversion(frame, v, c); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoContext.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoContext.java index bef642e8b3d3..a830790958d4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoContext.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoContext.java @@ -304,10 +304,10 @@ private static void reportSlowContextAccess(Node n) { var ex = new AssertionError( """ - no root node for {n} - with section: {s} - with root nodes: {r} - """ + no root node for {n} + with section: {s} + with root nodes: {r} + """ .replace("{n}", "" + n) .replace("{s}", "" + (n != null ? n.getEncapsulatingSourceSection() : null)) .replace("{r}", "" + (n != null ? n.getRootNode() : null))); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoPolyglotJava.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoPolyglotJava.java index 9fe0b875abe4..c5dacc966e74 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoPolyglotJava.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/EnsoPolyglotJava.java @@ -295,8 +295,9 @@ private static final class CtxData { switch (libState.length) { case 2 -> hostClassLoading.putIfAbsent(libState[0], libState[1]); case 1 -> hostClassLoading.putIfAbsent("", libState[0]); - default -> throw new IllegalStateException( - "Expecting []:hosted|guest, but was: " + entry); + default -> + throw new IllegalStateException( + "Expecting []:hosted|guest, but was: " + entry); } } assert hostClassLoading.containsKey(""); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapRemoveNode.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapRemoveNode.java index 3f1673e27b8d..db61568df5ee 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapRemoveNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapRemoveNode.java @@ -22,7 +22,8 @@ @BuiltinMethod( type = "Dictionary", name = "remove_builtin", - description = """ + description = + """ Removes an entry from this map specified with the key. """) @GenerateUncached diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapToTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapToTextNode.java index 694554819ceb..021dab0b1292 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapToTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/hash/HashMapToTextNode.java @@ -15,7 +15,8 @@ @BuiltinMethod( type = "Dictionary", name = "to_text", - description = """ + description = + """ Returns text representation of this hash map """, autoRegister = false) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java index d5b9a4c1ec28..112165e04cef 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java @@ -1,12 +1,5 @@ package org.enso.interpreter.runtime.data.text; -import java.util.ArrayDeque; - -import org.enso.interpreter.dsl.Builtin; -import org.enso.interpreter.node.expression.builtin.text.util.ToJavaStringNode; -import org.enso.interpreter.runtime.builtin.BuiltinObject; -import org.enso.polyglot.common_utils.Core_Text_Utils; - import com.ibm.icu.text.Normalizer2; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; @@ -15,6 +8,11 @@ import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.strings.TruffleString; import com.oracle.truffle.api.strings.TruffleString.Encoding; +import java.util.ArrayDeque; +import org.enso.interpreter.dsl.Builtin; +import org.enso.interpreter.node.expression.builtin.text.util.ToJavaStringNode; +import org.enso.interpreter.runtime.builtin.BuiltinObject; +import org.enso.polyglot.common_utils.Core_Text_Utils; /** Runtime representation of Enso's Text. */ @ExportLibrary(InteropLibrary.class) @@ -42,18 +40,18 @@ protected String builtinName() { @Builtin.Method( description = """ - Computes the number of characters in the text. + Computes the number of characters in the text. - ! What is a Character? - A character is defined as an Extended Grapheme Cluster, see Unicode - Standard Annex 29. This is the smallest unit that still has semantic - meaning in most text-processing applications. + ! What is a Character? + A character is defined as an Extended Grapheme Cluster, see Unicode + Standard Annex 29. This is the smallest unit that still has semantic + meaning in most text-processing applications. - > Example - Getting the length of the string "건반(Korean)". + > Example + Getting the length of the string "건반(Korean)". - "건반(Korean)".length - """) + "건반(Korean)".length + """) public long length() { int l = length; if (l == -1) { @@ -66,13 +64,13 @@ public long length() { @Builtin.Method( description = """ - Checks whether this text is in FCD normalized form. + Checks whether this text is in FCD normalized form. - > Example - Check if the string is normalized + > Example + Check if the string is normalized - "14.95€".is_normalized - """) + "14.95€".is_normalized + """) public boolean is_normalized() { return switch (fcdNormalized) { case 1 -> true; @@ -208,9 +206,9 @@ String toDisplayString( @Override public String toString() { return switch (this.contents) { - case String s -> s; - case ConcatRope r -> flattenAndSetContent(r); - case null, default -> throw new NullPointerException(); + case String s -> s; + case ConcatRope r -> flattenAndSetContent(r); + case null, default -> throw new NullPointerException(); }; } @@ -227,12 +225,12 @@ private String flattenAndSetContent(Object c) { workStack.push(c); while (!workStack.isEmpty()) { switch (workStack.pop()) { - case String s -> bldr.append(s); - case ConcatRope rope -> { - workStack.push(rope.right()); - workStack.push(rope.left()); - } - case null, default -> throw new NullPointerException(); + case String s -> bldr.append(s); + case ConcatRope rope -> { + workStack.push(rope.right()); + workStack.push(rope.left()); + } + case null, default -> throw new NullPointerException(); } } var result = bldr.toString(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java index 7c5702c39c0a..632af780f085 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java @@ -1,10 +1,21 @@ package org.enso.interpreter.runtime.scope; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.TruffleFile; +import com.oracle.truffle.api.dsl.Bind; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.interop.ArityException; +import com.oracle.truffle.api.interop.InteropLibrary; +import com.oracle.truffle.api.interop.UnknownIdentifierException; +import com.oracle.truffle.api.interop.UnsupportedMessageException; +import com.oracle.truffle.api.interop.UnsupportedTypeException; +import com.oracle.truffle.api.library.ExportLibrary; +import com.oracle.truffle.api.library.ExportMessage; +import com.oracle.truffle.api.nodes.Node; import java.io.File; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ExecutionException; - import org.enso.common.MethodNames; import org.enso.compiler.PackageRepository; import org.enso.editions.LibraryName; @@ -20,20 +31,6 @@ import org.enso.pkg.Package; import org.enso.pkg.QualifiedName; import org.enso.scala.wrapper.ScalaConversions; - -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.TruffleFile; -import com.oracle.truffle.api.dsl.Bind; -import com.oracle.truffle.api.dsl.Specialization; -import com.oracle.truffle.api.interop.ArityException; -import com.oracle.truffle.api.interop.InteropLibrary; -import com.oracle.truffle.api.interop.UnknownIdentifierException; -import com.oracle.truffle.api.interop.UnsupportedMessageException; -import com.oracle.truffle.api.interop.UnsupportedTypeException; -import com.oracle.truffle.api.library.ExportLibrary; -import com.oracle.truffle.api.library.ExportMessage; -import com.oracle.truffle.api.nodes.Node; - import scala.Option; /** Represents the top scope of Enso execution, containing all the importable modules. */ @@ -179,7 +176,8 @@ private static Object findNativeLibrary(Object[] arguments, EnsoContext context) var libname = arguments[0].toString(); var pkgRepo = context.getPackageRepository(); for (var pkg : pkgRepo.getLoadedPackagesJava()) { - var libPath = NativeLibraryFinder.findNativeLibrary(libname, pkg, TruffleFileSystem.INSTANCE); + var libPath = + NativeLibraryFinder.findNativeLibrary(libname, pkg, TruffleFileSystem.INSTANCE); if (libPath != null) { return libPath; } @@ -208,11 +206,12 @@ private static Object compile(Object[] arguments, EnsoContext context) switch (arguments.length) { case 2 -> { shouldCompileDependencies = Boolean.TRUE.equals(arguments[0]); - generateDocs = switch (arguments[1]) { - case Boolean b when !b -> Option.empty(); - case String s -> Option.apply(s); - default -> Option.empty(); - }; + generateDocs = + switch (arguments[1]) { + case Boolean b when !b -> Option.empty(); + case String s -> Option.apply(s); + default -> Option.empty(); + }; } default -> { shouldCompileDependencies = Types.extractArguments(arguments, Boolean.class); @@ -235,8 +234,7 @@ private static Object compile(Object[] arguments, EnsoContext context) } @Specialization - static Object doInvoke( - TopLevelScope scope, String member, Object[] arguments, @Bind Node node) + static Object doInvoke(TopLevelScope scope, String member, Object[] arguments, @Bind Node node) throws UnknownIdentifierException, ArityException, UnsupportedTypeException { var ctx = EnsoContext.get(node); switch (member) { diff --git a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java index c6ef343d058d..916949e1098d 100644 --- a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java +++ b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java @@ -239,9 +239,10 @@ public List visitAnnotation(AnnotationMirror a, Object o) { switch (name) { case FROM_ELEMENT_NAME -> valueFrom = entry.getValue().accept(typeVisitor, null); case TO_ELEMENT_NAME -> valueTo = entry.getValue().accept(typeVisitor, null); - default -> processingEnvironment - .getMessager() - .printMessage(Kind.ERROR, "Unknown annotation element name: " + name); + default -> + processingEnvironment + .getMessager() + .printMessage(Kind.ERROR, "Unknown annotation element name: " + name); } } if (valueFrom != null) { diff --git a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/TypeWithKind.java b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/TypeWithKind.java index 00499d8867bb..a6ec1a1e2d45 100644 --- a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/TypeWithKind.java +++ b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/TypeWithKind.java @@ -26,10 +26,10 @@ boolean isValidGuestType(ProcessingEnvironment env) { var typeMirror = switch (baseType) { case "long" -> env.getTypeUtils().getPrimitiveType(javax.lang.model.type.TypeKind.LONG); - case "double" -> env.getTypeUtils() - .getPrimitiveType(javax.lang.model.type.TypeKind.DOUBLE); - case "boolean" -> env.getTypeUtils() - .getPrimitiveType(javax.lang.model.type.TypeKind.BOOLEAN); + case "double" -> + env.getTypeUtils().getPrimitiveType(javax.lang.model.type.TypeKind.DOUBLE); + case "boolean" -> + env.getTypeUtils().getPrimitiveType(javax.lang.model.type.TypeKind.BOOLEAN); default -> { var less = baseType.indexOf('<'); var erased = less == -1 ? baseType : baseType.substring(0, less); diff --git a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/impl/BuiltinsProcessor.java b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/impl/BuiltinsProcessor.java index f2796bf971aa..d4d693330afb 100644 --- a/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/impl/BuiltinsProcessor.java +++ b/lib/java/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/impl/BuiltinsProcessor.java @@ -131,19 +131,21 @@ private void generateBuiltinType( var fqn = processingEnv.getElementUtils().getBinaryName(forElement); out.println(" super(\"" + fqn + "\");"); out.println(" }"); - out.println(""" - @Override - public boolean containsValues() { - """); + out.println( + """ + @Override + public boolean containsValues() { + """); if (containsValues) { out.println(" return true;"); } else { out.println(" return false;"); } - out.println(""" - } - } - """); + out.println( + """ + } + } + """); } } diff --git a/lib/java/jvm-interop/src/main/java/org/enso/jvm/interop/impl/OtherJvmObject.java b/lib/java/jvm-interop/src/main/java/org/enso/jvm/interop/impl/OtherJvmObject.java index f5f4ddafec82..42f214762c68 100644 --- a/lib/java/jvm-interop/src/main/java/org/enso/jvm/interop/impl/OtherJvmObject.java +++ b/lib/java/jvm-interop/src/main/java/org/enso/jvm/interop/impl/OtherJvmObject.java @@ -1,6 +1,5 @@ package org.enso.jvm.interop.impl; - import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.interop.InteropLibrary; @@ -304,7 +303,7 @@ static Object writeReplace(Object obj, BiFunction var iop = InteropLibrary.getUncached(); var mask = OtherInteropType.findType(foreign); if (isHostNull(mask, foreign)) { - yield new OtherJvmObject(null, 0, mask); + yield new OtherJvmObject(null, 0, mask); } var meta = OtherInteropType.isMetaObject(mask); var id = registerObject.apply(foreign, meta); @@ -333,7 +332,8 @@ private static boolean isHostNull(short mask, Object foreign) { var iop = InteropLibrary.getUncached(); if (OtherInteropType.isNull(mask)) { try { - if (iop.hasLanguage(foreign) && iop.getLanguage(foreign).getSimpleName().equals("HostLanguage")) { + if (iop.hasLanguage(foreign) + && iop.getLanguage(foreign).getSimpleName().equals("HostLanguage")) { return true; } } catch (UnsupportedMessageException ex) { diff --git a/lib/java/os-environment/src/main/java/org/enso/os/environment/chdir/WorkingDirectory.java b/lib/java/os-environment/src/main/java/org/enso/os/environment/chdir/WorkingDirectory.java index 665c994df19e..f06c9f74bcf8 100644 --- a/lib/java/os-environment/src/main/java/org/enso/os/environment/chdir/WorkingDirectory.java +++ b/lib/java/os-environment/src/main/java/org/enso/os/environment/chdir/WorkingDirectory.java @@ -92,9 +92,8 @@ public final String parentFile(String path) { private static boolean isPathAbsolute(String path) { return switch (Platform.getOperatingSystem()) { case LINUX, MACOS -> path.charAt(0) == Platform.separatorChar(); - case WINDOWS -> path.length() > 2 - && path.charAt(1) == ':' - && path.charAt(2) == Platform.separatorChar(); + case WINDOWS -> + path.length() > 2 && path.charAt(1) == ':' && path.charAt(2) == Platform.separatorChar(); }; } } diff --git a/lib/java/persistance-dsl/src/main/java/org/enso/persist/impl/PersistableProcessor.java b/lib/java/persistance-dsl/src/main/java/org/enso/persist/impl/PersistableProcessor.java index b74dc559a414..320f82f5e8ab 100644 --- a/lib/java/persistance-dsl/src/main/java/org/enso/persist/impl/PersistableProcessor.java +++ b/lib/java/persistance-dsl/src/main/java/org/enso/persist/impl/PersistableProcessor.java @@ -275,21 +275,19 @@ && isVisibleFrom(e, orig)) } } else switch (v.asType().getKind()) { - case BOOLEAN -> w.append(" var ") - .append(v.getSimpleName()) - .append(" = in.readBoolean();\n"); - case BYTE -> w.append(" var ") - .append(v.getSimpleName()) - .append(" = in.readByte();\n"); - case INT -> w.append(" var ") - .append(v.getSimpleName()) - .append(" = in.readInt();\n"); - case LONG -> w.append(" var ") - .append(v.getSimpleName()) - .append(" = in.readLong();\n"); - default -> processingEnv - .getMessager() - .printMessage(Kind.ERROR, "Unsupported primitive type: " + v.asType().getKind()); + case BOOLEAN -> + w.append(" var ").append(v.getSimpleName()).append(" = in.readBoolean();\n"); + case BYTE -> + w.append(" var ").append(v.getSimpleName()).append(" = in.readByte();\n"); + case INT -> + w.append(" var ").append(v.getSimpleName()).append(" = in.readInt();\n"); + case LONG -> + w.append(" var ").append(v.getSimpleName()).append(" = in.readLong();\n"); + default -> + processingEnv + .getMessager() + .printMessage( + Kind.ERROR, "Unsupported primitive type: " + v.asType().getKind()); } } w.append(" return new ").append(typeElemName).append("(\n"); @@ -357,21 +355,19 @@ && isVisibleFrom(e, orig)) } } else switch (v.asType().getKind()) { - case BOOLEAN -> w.append(" out.writeBoolean(obj.") - .append(v.getSimpleName()) - .append("());\n"); - case BYTE -> w.append(" out.writeByte(obj.") - .append(v.getSimpleName()) - .append("());\n"); - case INT -> w.append(" out.writeInt(obj.") - .append(v.getSimpleName()) - .append("());\n"); - case LONG -> w.append(" out.writeLong(obj.") - .append(v.getSimpleName()) - .append("());\n"); - default -> processingEnv - .getMessager() - .printMessage(Kind.ERROR, "Unsupported primitive type: " + v.asType().getKind()); + case BOOLEAN -> + w.append(" out.writeBoolean(obj.").append(v.getSimpleName()).append("());\n"); + case BYTE -> + w.append(" out.writeByte(obj.").append(v.getSimpleName()).append("());\n"); + case INT -> + w.append(" out.writeInt(obj.").append(v.getSimpleName()).append("());\n"); + case LONG -> + w.append(" out.writeLong(obj.").append(v.getSimpleName()).append("());\n"); + default -> + processingEnv + .getMessager() + .printMessage( + Kind.ERROR, "Unsupported primitive type: " + v.asType().getKind()); } } } else { diff --git a/lib/java/persistance/src/main/java/org/enso/persist/Persistable.java b/lib/java/persistance/src/main/java/org/enso/persist/Persistable.java index 53cc082b3c64..db0a04aa8630 100644 --- a/lib/java/persistance/src/main/java/org/enso/persist/Persistable.java +++ b/lib/java/persistance/src/main/java/org/enso/persist/Persistable.java @@ -8,6 +8,7 @@ * Annotation for an automatic persistance of a class. Use to generate implementation and * registration of {@link Persistance} subclass to read and write simple records and case classes: *
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="annotation"} */ @Target(ElementType.TYPE) @@ -18,8 +19,12 @@ * The class to generate {@link Persistance} for. If the value is omitted then the code is * generated for the class that is annotated by this annotation. Example of multiple * {@code @Persistable} annotations on a single element.
- * {@snippet file="org/enso/persist/PersistanceTest.java" region="annotation"}
+ * + * {@snippet file="org/enso/persist/PersistanceTest.java" region="annotation"} + * + *
* Example of self annotated class:
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="self-annotation"} * * @return the class to generate read/write persistance code for diff --git a/lib/java/persistance/src/main/java/org/enso/persist/Persistance.java b/lib/java/persistance/src/main/java/org/enso/persist/Persistance.java index 8ed00b91558c..c679f153eb8a 100644 --- a/lib/java/persistance/src/main/java/org/enso/persist/Persistance.java +++ b/lib/java/persistance/src/main/java/org/enso/persist/Persistance.java @@ -13,10 +13,12 @@ /** * Central persistance class. Use {@link Pool#write(java.lang.Object, java.util.function.Function) * write} method to turn a graph of JVM objects into a {@code byte[]}.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="write"} * *

Use sibling {@link Persistance.Pool#read read} method to read the byte buffer back into their * memory representation.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"} * *

Manual Persistance

@@ -25,7 +27,10 @@ * one to implement the persistance manually. For each class that one wants to support, one has to * subclass {@link Persistance} and implement its {@link Persistance#writeObject} and {@link * Persistance#readObject} method.
- * {@snippet file="org/enso/persist/PersistanceTest.java" region="manual"}
+ * + * {@snippet file="org/enso/persist/PersistanceTest.java" region="manual"} + * + *
* There is a semi-automatic way to generate such subclasses of {@link Persistance} via the {@link * Persistable @Persistable} annotation. * @@ -39,7 +44,10 @@ public abstract class Persistance implements Cloneable { /** * Constructor for subclasses to register persistance for certain {@code clazz}. Sample * registration:
- * {@snippet file="org/enso/persist/PersistanceTest.java" region="manual"}
+ * + * {@snippet file="org/enso/persist/PersistanceTest.java" region="manual"} + * + *
* Each persistance requires unique ID. A stream created by {@link Pool#write(Object, * Function)} and read by {@link Pool#read(byte[], Function)} * contains a header derived from the all the IDs present in the system. When versioning the @@ -260,7 +268,11 @@ private static Pool newWithResolveAndReplace( /** * Read object written down by {@link #write} from an array.
- * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"}
+ * + * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"} + * + *
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"} * * @param arr the stored bytes diff --git a/lib/java/persistance/src/main/java/org/enso/persist/package-info.java b/lib/java/persistance/src/main/java/org/enso/persist/package-info.java index f63a06efbcfa..0888085735f7 100644 --- a/lib/java/persistance/src/main/java/org/enso/persist/package-info.java +++ b/lib/java/persistance/src/main/java/org/enso/persist/package-info.java @@ -3,10 +3,12 @@ * {@link Persistance.Pool} - usually generated by {@link Persistable} * annotation automatically. Use pool's {@link Persistance.Pool#write write} method to turn a * graph of JVM objects into a {@code byte[]}.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="write"} * *

Use sibling pool's {@link Persistance.Pool#read read} method to read the byte buffer back into * their memory representation.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"} * *

Laziness

@@ -22,6 +24,7 @@ * associated annotation processor that generates the necessary {@link Persistance} subclass based * on the "richest" constructor in the class to be persisted. This approach seems to work well for * Java records and Scala case classes.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="annotation"} * *

The {@link Persistance.Pool}

@@ -32,7 +35,9 @@ * Persistance.Pool#read Persistables.POOL.read} and {@link Persistance.Pool#write * Persistables.POOL.write} methods. * - *

{@snippet file="org/enso/persist/PersistanceTest.java" region="read"} + *

+ * + * {@snippet file="org/enso/persist/PersistanceTest.java" region="read"} * *

Use {@link Persistance.Pool#merge} to compose pools from multiple packages into a single * combined pool of instances. @@ -43,6 +48,7 @@ * one to implement the persistance manually. For each class one wants to serde, one has to * implement a subclass of {@link Persistance} and implement its {@link Persistance#writeObject} and * {@link Persistance#readObject} methods.
+ * * {@snippet file="org/enso/persist/PersistanceTest.java" region="manual"} */ package org.enso.persist; diff --git a/lib/java/test-utils/src/main/java/org/enso/test/utils/ProjectUtils.java b/lib/java/test-utils/src/main/java/org/enso/test/utils/ProjectUtils.java index 87a39c225be5..457d5c092e15 100644 --- a/lib/java/test-utils/src/main/java/org/enso/test/utils/ProjectUtils.java +++ b/lib/java/test-utils/src/main/java/org/enso/test/utils/ProjectUtils.java @@ -56,11 +56,12 @@ public static void createProject(String projName, Set modules, Pat "Project directory " + projDir + " must already be created"); } var projYaml = - """ +""" name: %s version: 0.0.1 prefer-local-libraries: true - """.formatted(projName); +""" + .formatted(projName); var yamlPath = projDir.resolve("package.yaml"); Files.writeString(yamlPath, projYaml); assert yamlPath.toFile().exists(); diff --git a/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/ParserPolyfillTest.java b/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/ParserPolyfillTest.java index 0c10ecdf9733..e65cfd3a8386 100644 --- a/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/ParserPolyfillTest.java +++ b/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/ParserPolyfillTest.java @@ -41,7 +41,8 @@ public void tearDown() throws InterruptedException { @Test public void parseModule() throws Exception { - var code = """ + var code = + """ const arr = parse_module(`main = 1 + 2`) arr.buffer """; @@ -53,7 +54,8 @@ public void parseModule() throws Exception { @Test public void parseBlock() throws Exception { - var code = """ + var code = + """ const arr = parse_block(`value = 1 + 2`) arr.buffer """; @@ -65,7 +67,8 @@ public void parseBlock() throws Exception { @Test public void xxHash128() throws Exception { - var code = """ + var code = + """ xxHash128(`main = 1 + 2`) """; @@ -76,7 +79,8 @@ public void xxHash128() throws Exception { @Test public void isIdentOrOperator() throws Exception { - var code = """ + var code = + """ is_ident_or_operator(`ident`) """; diff --git a/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/web/ZlibTest.java b/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/web/ZlibTest.java index 6ee4ff2d9afb..f4aeac35b2d9 100644 --- a/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/web/ZlibTest.java +++ b/lib/java/ydoc-polyfill/src/test/java/org/enso/ydoc/polyfill/web/ZlibTest.java @@ -59,10 +59,10 @@ public void bufferFrom() throws Exception { public void bufferToHexString() throws Exception { var code = """ - const buf = Buffer.from('hello world', 'utf8'); - // Prints: 68656c6c6f20776f726c64 - buf.toString('hex') - """; + const buf = Buffer.from('hello world', 'utf8'); + // Prints: 68656c6c6f20776f726c64 + buf.toString('hex') + """; var result = CompletableFuture.supplyAsync(() -> context.eval("js", code), executor).get(); @@ -73,22 +73,22 @@ public void bufferToHexString() throws Exception { public void bufferFromArrayNoArgs() throws Exception { var code = """ - const arr = new Uint16Array(2); + const arr = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; + arr[0] = 5000; + arr[1] = 4000; - // Shares memory with `arr`. - const buf = Buffer.from(arr.buffer); + // Shares memory with `arr`. + const buf = Buffer.from(arr.buffer); - const t1 = buf.toString("hex"); // Prints: + const t1 = buf.toString("hex"); // Prints: - // Changing the original Uint16Array changes the Buffer also. - arr[1] = 6000; + // Changing the original Uint16Array changes the Buffer also. + arr[1] = 6000; - const t2 = buf.toString("hex"); // Prints: - [buf, t1, t2] - """; + const t2 = buf.toString("hex"); // Prints: + [buf, t1, t2] + """; var result = CompletableFuture.supplyAsync(() -> context.eval("js", code), executor).get(); assertTrue("It is an array", result.hasArrayElements()); @@ -105,22 +105,22 @@ public void bufferFromArrayNoArgs() throws Exception { public void bufferFromArrayOneArg() throws Exception { var code = """ - const arr = new Uint16Array(2); + const arr = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; + arr[0] = 5000; + arr[1] = 4000; - // Shares memory with `arr`. - const buf = Buffer.from(arr.buffer, 1); + // Shares memory with `arr`. + const buf = Buffer.from(arr.buffer, 1); - const t1 = buf.toString("hex"); // Prints: + const t1 = buf.toString("hex"); // Prints: - // Changing the original Uint16Array changes the Buffer also. - arr[1] = 6000; + // Changing the original Uint16Array changes the Buffer also. + arr[1] = 6000; - const t2 = buf.toString("hex"); // Prints: - [buf, t1, t2] - """; + const t2 = buf.toString("hex"); // Prints: + [buf, t1, t2] + """; var result = CompletableFuture.supplyAsync(() -> context.eval("js", code), executor).get(); assertTrue("It is an array", result.hasArrayElements()); @@ -137,22 +137,22 @@ public void bufferFromArrayOneArg() throws Exception { public void bufferFromArrayTwoArgs() throws Exception { var code = """ - const arr = new Uint16Array(2); + const arr = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; + arr[0] = 5000; + arr[1] = 4000; - // Shares memory with `arr`. - const buf = Buffer.from(arr.buffer, 1, 2); + // Shares memory with `arr`. + const buf = Buffer.from(arr.buffer, 1, 2); - const t1 = buf.toString("hex"); // Prints: + const t1 = buf.toString("hex"); // Prints: - // Changing the original Uint16Array changes the Buffer also. - arr[1] = 6000; + // Changing the original Uint16Array changes the Buffer also. + arr[1] = 6000; - const t2 = buf.toString("hex"); // Prints: - [buf, t1, t2] - """; + const t2 = buf.toString("hex"); // Prints: + [buf, t1, t2] + """; var result = CompletableFuture.supplyAsync(() -> context.eval("js", code), executor).get(); assertTrue("It is an array", result.hasArrayElements()); @@ -191,14 +191,14 @@ public void bufferFromBase64() throws Exception { public void bufferFromInvalid() throws Exception { var code = """ - result = '' - try { - Buffer.from(TEXT, 'invalid').toString() - } catch (e) { - result = e.message - } - result - """; + result = '' + try { + Buffer.from(TEXT, 'invalid').toString() + } catch (e) { + result = e.message + } + result + """; context.getBindings("js").putMember("TEXT", TEXT); @@ -233,14 +233,14 @@ public void bufferToBase64() throws Exception { public void bufferToInvalid() throws Exception { var code = """ - result = '' - try { - Buffer.from(TEXT).toString('invalid') - } catch (e) { - result = e.message - } - result - """; + result = '' + try { + Buffer.from(TEXT).toString('invalid') + } catch (e) { + result = e.message + } + result + """; context.getBindings("js").putMember("TEXT", TEXT); @@ -253,9 +253,9 @@ public void bufferToInvalid() throws Exception { public void bufferToFromBase64() throws Exception { var code = """ - let textBase64 = Buffer.from(TEXT).toString('base64') - Buffer.from(textBase64, 'base64').toString() - """; + let textBase64 = Buffer.from(TEXT).toString('base64') + Buffer.from(textBase64, 'base64').toString() + """; context.getBindings("js").putMember("TEXT", TEXT); @@ -268,9 +268,9 @@ public void bufferToFromBase64() throws Exception { public void zlibDeflateSync() throws Exception { var code = """ - let buffer = Buffer.from(TEXT) - zlib.deflateSync(buffer).toString('base64') - """; + let buffer = Buffer.from(TEXT) + zlib.deflateSync(buffer).toString('base64') + """; context.getBindings("js").putMember("TEXT", TEXT); @@ -283,9 +283,9 @@ public void zlibDeflateSync() throws Exception { public void zlibInflateSync() throws Exception { var code = """ - let buffer = Buffer.from(TEXT_DEFLATED, 'base64') - zlib.inflateSync(buffer).toString() - """; + let buffer = Buffer.from(TEXT_DEFLATED, 'base64') + zlib.inflateSync(buffer).toString() + """; context.getBindings("js").putMember("TEXT_DEFLATED", TEXT_DEFLATED); @@ -298,9 +298,9 @@ public void zlibInflateSync() throws Exception { public void zlibDeflateInflate() throws Exception { var code = """ - let buffer = Buffer.from(TEXT) - zlib.inflateSync(zlib.deflateSync(buffer)).toString() - """; + let buffer = Buffer.from(TEXT) + zlib.inflateSync(zlib.deflateSync(buffer)).toString() + """; context.getBindings("js").putMember("TEXT", TEXT); @@ -313,15 +313,15 @@ public void zlibDeflateInflate() throws Exception { public void zlibInflateCorrupted() throws Exception { var code = """ - let buffer = Buffer.from('corrupted') - let result = '' - try { - zlib.inflateSync(buffer).toString() - } catch (e) { - result = e.message - } - result - """; + let buffer = Buffer.from('corrupted') + let result = '' + try { + zlib.inflateSync(buffer).toString() + } catch (e) { + result = e.message + } + result + """; context.getBindings("js").putMember("TEXT", TEXT); diff --git a/lib/scala/bench-processor/src/main/java/org/enso/benchmarks/processor/SpecCollector.java b/lib/scala/bench-processor/src/main/java/org/enso/benchmarks/processor/SpecCollector.java index c8deeff55202..164c19c1b925 100644 --- a/lib/scala/bench-processor/src/main/java/org/enso/benchmarks/processor/SpecCollector.java +++ b/lib/scala/bench-processor/src/main/java/org/enso/benchmarks/processor/SpecCollector.java @@ -333,92 +333,92 @@ private void generateClassForGroup( out.println( """ - private final class LogHandler extends Handler { - private final Handler fallbackHandler; - - LogHandler(Handler fallbackHandler) { - this.fallbackHandler = fallbackHandler; - } - - @Override - public void publish(LogRecord lr) { - if ("engine".equals(lr.getLoggerName())) { - messages.add(lr); - } else { - fallbackHandler.publish(lr); - } - } - - @Override - public void flush() { - fallbackHandler.flush(); - } - - @Override - public void close() { - fallbackHandler.close(); - } - } - - @Setup(org.openjdk.jmh.annotations.Level.Iteration) - public void clearCompilationMessages(IterationParams it) { - var round = round(it); - if (!messages.isEmpty()) { - compilationLog.append("Before " + it.getType() + "#" + round + ". "); - compilationLog.append("Cleaning " + messages.size() + " compilation messages\\n"); - messages.clear(); - } - } - - private int round(IterationParams it) { - return switch (it.getType()) { - case WARMUP -> ++warmupCounter; - case MEASUREMENT -> ++measurementCounter; - }; - } - - private void dumpMessages() { - for (var lr : messages) { - compilationLog.append(lr.getMessage() + "\\n"); - compilationMessagesFound = true; - } - } - - @TearDown(org.openjdk.jmh.annotations.Level.Iteration) - public void dumpCompilationMessages(IterationParams it) { - switch (it.getType()) { - case MEASUREMENT -> { - compilationLog.append("After " + it.getType() + "#" + measurementCounter + ". "); - if (!messages.isEmpty()) { - compilationLog.append("Dumping " + messages.size() + " compilation messages:\\n"); - dumpMessages(); - } else { - compilationLog.append("No compilation messages.\\n"); - } - } - } - } - - @TearDown - public void checkNoTruffleCompilation(BenchmarkParams params) { - if (compilationMessagesFound) { - var limit = Boolean.getBoolean("bench.all") ? 10 : Integer.MAX_VALUE; - for (var l : compilationLog.toString().split("\\n")) { - var pipe = l.indexOf('|'); - if (pipe > 0) { - l = l.substring(0, pipe); - } - System.out.println(l); - if (limit-- <= 0) { - System.out.println("... to see more use:"); - System.out.println("benchOnly " + params.getBenchmark()); - break; - } - } - } - } - - """); + private final class LogHandler extends Handler { + private final Handler fallbackHandler; + + LogHandler(Handler fallbackHandler) { + this.fallbackHandler = fallbackHandler; + } + + @Override + public void publish(LogRecord lr) { + if ("engine".equals(lr.getLoggerName())) { + messages.add(lr); + } else { + fallbackHandler.publish(lr); + } + } + + @Override + public void flush() { + fallbackHandler.flush(); + } + + @Override + public void close() { + fallbackHandler.close(); + } + } + + @Setup(org.openjdk.jmh.annotations.Level.Iteration) + public void clearCompilationMessages(IterationParams it) { + var round = round(it); + if (!messages.isEmpty()) { + compilationLog.append("Before " + it.getType() + "#" + round + ". "); + compilationLog.append("Cleaning " + messages.size() + " compilation messages\\n"); + messages.clear(); + } + } + + private int round(IterationParams it) { + return switch (it.getType()) { + case WARMUP -> ++warmupCounter; + case MEASUREMENT -> ++measurementCounter; + }; + } + + private void dumpMessages() { + for (var lr : messages) { + compilationLog.append(lr.getMessage() + "\\n"); + compilationMessagesFound = true; + } + } + + @TearDown(org.openjdk.jmh.annotations.Level.Iteration) + public void dumpCompilationMessages(IterationParams it) { + switch (it.getType()) { + case MEASUREMENT -> { + compilationLog.append("After " + it.getType() + "#" + measurementCounter + ". "); + if (!messages.isEmpty()) { + compilationLog.append("Dumping " + messages.size() + " compilation messages:\\n"); + dumpMessages(); + } else { + compilationLog.append("No compilation messages.\\n"); + } + } + } + } + + @TearDown + public void checkNoTruffleCompilation(BenchmarkParams params) { + if (compilationMessagesFound) { + var limit = Boolean.getBoolean("bench.all") ? 10 : Integer.MAX_VALUE; + for (var l : compilationLog.toString().split("\\n")) { + var pipe = l.indexOf('|'); + if (pipe > 0) { + l = l.substring(0, pipe); + } + System.out.println(l); + if (limit-- <= 0) { + System.out.println("... to see more use:"); + System.out.println("benchOnly " + params.getBenchmark()); + break; + } + } + } + } + + """); // Benchmark methods for (var specJavaName : specJavaNames) { out.println(); diff --git a/lib/scala/version-output/src/main/java/org/enso/version/VersionDescription.java b/lib/scala/version-output/src/main/java/org/enso/version/VersionDescription.java index bac9528e782d..aa00a045e312 100644 --- a/lib/scala/version-output/src/main/java/org/enso/version/VersionDescription.java +++ b/lib/scala/version-output/src/main/java/org/enso/version/VersionDescription.java @@ -91,9 +91,9 @@ public String asHumanReadableString() { runtimeDescription = String.format( """ - Running on: %s, %s, JDK %s - %s, %s (%s) - """, + Running on: %s, %s, JDK %s + %s, %s (%s) + """, vmName, vmVendor, jreVersion, osName, osVersion, osArch); } else if (enableNativeImageOSWorkaround) { // TODO [RW] Currently the `os.name` property seems to be set to the @@ -135,22 +135,22 @@ public String asJSONString() { runtimeDescription = String.format( """ - "osName": "%s", - "osVersion": "%s", - "osArch": "%s" - """, + "osName": "%s", + "osVersion": "%s", + "osArch": "%s" + """, osName, osVersion, osArch); } else { runtimeDescription = String.format( """ - "vmName": "%s", - "vmVendor": "%s", - "jreVersion": "%s", - "osName": "%s", - "osVersion": "%s", - "osArch": "%s" - """, + "vmName": "%s", + "vmVendor": "%s", + "jreVersion": "%s", + "osName": "%s", + "osVersion": "%s", + "osArch": "%s" + """, vmName, vmVendor, jreVersion, osName, osVersion, osArch); } var parameters = formatParameters(VersionDescription::formatParameterAsJSONString, ",\n"); diff --git a/std-bits/base/src/main/java/org/enso/base/enso_cloud/SecretValueResolver.java b/std-bits/base/src/main/java/org/enso/base/enso_cloud/SecretValueResolver.java index e9d866cf7b99..1cf78dbcdd03 100644 --- a/std-bits/base/src/main/java/org/enso/base/enso_cloud/SecretValueResolver.java +++ b/std-bits/base/src/main/java/org/enso/base/enso_cloud/SecretValueResolver.java @@ -10,18 +10,19 @@ sealed class SecretValueResolver permits EnsoSecretHelper, ExternalLibrarySecret protected static String resolveValue(HideableValue value) { return switch (value) { case HideableValue.PlainValue plainValue -> plainValue.value(); - case HideableValue.SecretValue secretValue -> EnsoSecretReader.INSTANCE.readSecret( - secretValue.secretId()); + case HideableValue.SecretValue secretValue -> + EnsoSecretReader.INSTANCE.readSecret(secretValue.secretId()); case HideableValue.ConcatValues concatValues -> { String left = resolveValue(concatValues.left()); String right = resolveValue(concatValues.right()); yield left + right; } - case HideableValue.Base64EncodeValue base64EncodeValue -> HideableValue.Base64EncodeValue - .encode(resolveValue(base64EncodeValue.value())); - case InterpretAsPrivateKey pk -> throw new IllegalStateException( - "InterpretAsPrivateKey can only be used in JDBC connections. This state should never be" - + " reached."); + case HideableValue.Base64EncodeValue base64EncodeValue -> + HideableValue.Base64EncodeValue.encode(resolveValue(base64EncodeValue.value())); + case InterpretAsPrivateKey pk -> + throw new IllegalStateException( + "InterpretAsPrivateKey can only be used in JDBC connections. This state should never" + + " be reached."); }; } } diff --git a/std-bits/base/src/main/java/org/enso/base/numeric/Decimal_Utils.java b/std-bits/base/src/main/java/org/enso/base/numeric/Decimal_Utils.java index d6a6f8ba0eea..da7a4813f5c4 100644 --- a/std-bits/base/src/main/java/org/enso/base/numeric/Decimal_Utils.java +++ b/std-bits/base/src/main/java/org/enso/base/numeric/Decimal_Utils.java @@ -17,7 +17,7 @@ public static Number fromString(String s) throws ParseException { try { return new BigDecimal(s); } catch (NumberFormatException e) { - var df = (DecimalFormat)DecimalFormat.getInstance(Locale.ROOT); + var df = (DecimalFormat) DecimalFormat.getInstance(Locale.ROOT); df.setParseBigDecimal(true); return df.parse(s); } diff --git a/std-bits/base/src/main/java/org/enso/base/parser/NumberWithSeparators.java b/std-bits/base/src/main/java/org/enso/base/parser/NumberWithSeparators.java index f3cd2bc1fa40..1328e3d08223 100644 --- a/std-bits/base/src/main/java/org/enso/base/parser/NumberWithSeparators.java +++ b/std-bits/base/src/main/java/org/enso/base/parser/NumberWithSeparators.java @@ -77,14 +77,16 @@ public static NumberWithSeparators fromSeparators(String thousand, String decima switch (thousands) { case Constants.NONE -> matchForNone(decimals); case Constants.UNKNOWN -> matchForUnknown(decimals); - case ',' -> switch (decimals) { - case Constants.UNKNOWN, Constants.NONE, '.' -> Optional.of(COMMA_DOT); - default -> Optional.empty(); - }; - case '.' -> switch (decimals) { - case Constants.UNKNOWN, Constants.NONE, ',' -> Optional.of(DOT_COMMA); - default -> Optional.empty(); - }; + case ',' -> + switch (decimals) { + case Constants.UNKNOWN, Constants.NONE, '.' -> Optional.of(COMMA_DOT); + default -> Optional.empty(); + }; + case '.' -> + switch (decimals) { + case Constants.UNKNOWN, Constants.NONE, ',' -> Optional.of(DOT_COMMA); + default -> Optional.empty(); + }; case ' ' -> matchForSpace(decimals); case '\'' -> matchForSwiss(decimals); case '_' -> matchForUnderscore(decimals); @@ -299,12 +301,14 @@ private NumberParseResult parseUnknownInteger( switch (separator) { case '.' -> DOT_COMMA; case ',' -> separatorCount == 1 ? COMMA_UNKNOWN : COMMA_DOT; - case ' ' -> (decimal == Constants.UNKNOWN - ? SPACE_UNKNOWN - : (decimal == '.' ? SPACE_DOT : SPACE_COMMA)); - case '\'' -> (decimal == Constants.UNKNOWN - ? SWISS_UNKNOWN - : (decimal == '.' ? SWISS_DOT : SWISS_COMMA)); + case ' ' -> + (decimal == Constants.UNKNOWN + ? SPACE_UNKNOWN + : (decimal == '.' ? SPACE_DOT : SPACE_COMMA)); + case '\'' -> + (decimal == Constants.UNKNOWN + ? SWISS_UNKNOWN + : (decimal == '.' ? SWISS_DOT : SWISS_COMMA)); default -> null; }; if (format == null) { @@ -445,12 +449,10 @@ private NumberParseResult parseUnknownDecimal( switch (firstSeparator) { case '.' -> secondSeparator == ',' ? DOT_COMMA : null; case ',' -> secondSeparator == '.' ? COMMA_DOT : null; - case ' ' -> secondSeparator == '.' - ? SPACE_DOT - : secondSeparator == ',' ? SPACE_COMMA : null; - case '\'' -> secondSeparator == '.' - ? SWISS_DOT - : secondSeparator == ',' ? SWISS_COMMA : null; + case ' ' -> + secondSeparator == '.' ? SPACE_DOT : secondSeparator == ',' ? SPACE_COMMA : null; + case '\'' -> + secondSeparator == '.' ? SWISS_DOT : secondSeparator == ',' ? SWISS_COMMA : null; default -> null; }; } else if (firstSeparator == '.') { diff --git a/std-bits/base/src/main/java/org/enso/base/polyglot/NumericConverter.java b/std-bits/base/src/main/java/org/enso/base/polyglot/NumericConverter.java index 8e4f5d38333c..c5b6e28bf40f 100644 --- a/std-bits/base/src/main/java/org/enso/base/polyglot/NumericConverter.java +++ b/std-bits/base/src/main/java/org/enso/base/polyglot/NumericConverter.java @@ -1,9 +1,8 @@ package org.enso.base.polyglot; -import org.graalvm.polyglot.Value; - import java.math.BigDecimal; import java.math.BigInteger; +import org.graalvm.polyglot.Value; /** * The numeric converter deals with conversions of Java numeric types to the two main types @@ -46,7 +45,8 @@ public static long coerceToLong(Object o) { case Integer x -> x.longValue(); case Short x -> x.longValue(); case Byte x -> x.longValue(); - default -> throw new UnsupportedOperationException("Cannot coerce " + o + " to a numeric type."); + default -> + throw new UnsupportedOperationException("Cannot coerce " + o + " to a numeric type."); }; } @@ -74,18 +74,18 @@ public static BigDecimal coerceToBigDecimal(Object o) { case Integer x -> BigDecimal.valueOf(x); case Short x -> BigDecimal.valueOf(x); case Byte x -> BigDecimal.valueOf(x); - default -> throw new UnsupportedOperationException("Cannot coerce " + o + " to a BigDecimal."); + default -> + throw new UnsupportedOperationException("Cannot coerce " + o + " to a BigDecimal."); }; } /** Returns true if the object is any supported number. */ public static boolean isCoercibleToDouble(Object o) { - return isFloatLike(o)|| isCoercibleToLong(o) || o instanceof BigInteger; + return isFloatLike(o) || isCoercibleToLong(o) || o instanceof BigInteger; } public static boolean isFloatLike(Object o) { - return o instanceof Double - || o instanceof Float; + return o instanceof Double || o instanceof Float; } /** diff --git a/std-bits/base/src/main/java/org/enso/base/time/EnsoDateTimeFormatterImpl.java b/std-bits/base/src/main/java/org/enso/base/time/EnsoDateTimeFormatterImpl.java index c260563292dc..29fcf80a161a 100644 --- a/std-bits/base/src/main/java/org/enso/base/time/EnsoDateTimeFormatterImpl.java +++ b/std-bits/base/src/main/java/org/enso/base/time/EnsoDateTimeFormatterImpl.java @@ -99,11 +99,12 @@ private String normaliseInput(String dateString) { public String describe() { return switch (formatterKind) { case SIMPLE -> "Date_Time_Formatter.from_simple_pattern " + getOriginalPattern(); - case ISO_WEEK_DATE -> "Date_Time_Formatter.from_iso_week_date_pattern " - + getOriginalPattern(); - case RAW_JAVA -> originalPattern != null - ? "Date_Time_Formatter.from_java " + getOriginalPattern() - : "Date_Time_Formatter.from_java " + formatter.toString(); + case ISO_WEEK_DATE -> + "Date_Time_Formatter.from_iso_week_date_pattern " + getOriginalPattern(); + case RAW_JAVA -> + originalPattern != null + ? "Date_Time_Formatter.from_java " + getOriginalPattern() + : "Date_Time_Formatter.from_java " + formatter.toString(); case CONSTANT -> "Date_Time_Formatter." + getOriginalPattern(); }; } @@ -113,8 +114,9 @@ public String toString() { return switch (formatterKind) { case SIMPLE -> originalPattern; case ISO_WEEK_DATE -> "(ISO Week Date Format) " + originalPattern; - case RAW_JAVA -> "(Java DateTimeFormatter) " - + (originalPattern != null ? originalPattern : formatter.toString()); + case RAW_JAVA -> + "(Java DateTimeFormatter) " + + (originalPattern != null ? originalPattern : formatter.toString()); case CONSTANT -> originalPattern; }; } diff --git a/std-bits/database/src/main/java/org/enso/database/JDBCProxy.java b/std-bits/database/src/main/java/org/enso/database/JDBCProxy.java index f76b0689ef44..292156ac9fb9 100644 --- a/std-bits/database/src/main/java/org/enso/database/JDBCProxy.java +++ b/std-bits/database/src/main/java/org/enso/database/JDBCProxy.java @@ -59,11 +59,12 @@ public static Connection getConnection(String url, List new LocalAuditedConnection(rawConnection); - case "cloud" -> new CloudAuditedConnection( - rawConnection, partitionedProperties.getRelatedAssetId()); + case "cloud" -> + new CloudAuditedConnection(rawConnection, partitionedProperties.getRelatedAssetId()); case null -> rawConnection; - default -> throw new IllegalArgumentException( - "Unknown audit mode: " + partitionedProperties.audited()); + default -> + throw new IllegalArgumentException( + "Unknown audit mode: " + partitionedProperties.audited()); }; } diff --git a/std-bits/database/src/main/java/org/enso/database/fetchers/ColumnFetcherFactory.java b/std-bits/database/src/main/java/org/enso/database/fetchers/ColumnFetcherFactory.java index 047e71f9f49e..1aa620f2518c 100644 --- a/std-bits/database/src/main/java/org/enso/database/fetchers/ColumnFetcherFactory.java +++ b/std-bits/database/src/main/java/org/enso/database/fetchers/ColumnFetcherFactory.java @@ -27,57 +27,58 @@ public ColumnFetcher forStorageType( case BooleanType bt -> new BooleanColumnFetcher(colIndex, columnName); case IntegerType it -> new LongColumnFetcher(colIndex, columnName, it, problemAggregator); case FloatType ft -> new DoubleColumnFetcher(colIndex, columnName, ft, problemAggregator); - case BigIntegerType bi -> new GenericColumnFetcher<>( - colIndex, columnName, bi, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - var bigDecimal = resultSet.getBigDecimal(index()); - return bigDecimal == null ? null : bigDecimal.toBigIntegerExact(); - } - }; - case BigDecimalType bd -> new GenericColumnFetcher<>( - colIndex, columnName, bd, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - return JDBCUtils.getBigDecimalHandleSpecialFloats(resultSet, index()); - } - }; - case TextType tt -> new GenericColumnFetcher<>( - colIndex, columnName, tt, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - return resultSet.getString(index()); - } - }; - case TimeOfDayType todt -> new GenericColumnFetcher<>( - colIndex, columnName, todt, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - return JDBCUtils.getLocalTime(resultSet, index()); - } - }; - case DateType dt -> new GenericColumnFetcher<>( - colIndex, columnName, dt, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - return JDBCUtils.getLocalDate(resultSet, index()); - } - }; - case DateTimeType dtt -> dtt.hasTimeZone() - ? new GenericColumnFetcher<>( - colIndex, columnName, DateTimeType.INSTANCE, problemAggregator) { + case BigIntegerType bi -> + new GenericColumnFetcher<>(colIndex, columnName, bi, problemAggregator) { @Override public Object getValue(ResultSet resultSet) throws SQLException { - return JDBCUtils.getLocalDateTimeAsZoned(resultSet, index()); + var bigDecimal = resultSet.getBigDecimal(index()); + return bigDecimal == null ? null : bigDecimal.toBigIntegerExact(); } - } - : new GenericColumnFetcher<>( - colIndex, columnName, DateTimeType.INSTANCE, problemAggregator) { + }; + case BigDecimalType bd -> + new GenericColumnFetcher<>(colIndex, columnName, bd, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + return JDBCUtils.getBigDecimalHandleSpecialFloats(resultSet, index()); + } + }; + case TextType tt -> + new GenericColumnFetcher<>(colIndex, columnName, tt, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + return resultSet.getString(index()); + } + }; + case TimeOfDayType todt -> + new GenericColumnFetcher<>(colIndex, columnName, todt, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + return JDBCUtils.getLocalTime(resultSet, index()); + } + }; + case DateType dt -> + new GenericColumnFetcher<>(colIndex, columnName, dt, problemAggregator) { @Override public Object getValue(ResultSet resultSet) throws SQLException { - return JDBCUtils.getZonedDateTime(resultSet, index()); + return JDBCUtils.getLocalDate(resultSet, index()); } }; + case DateTimeType dtt -> + dtt.hasTimeZone() + ? new GenericColumnFetcher<>( + colIndex, columnName, DateTimeType.INSTANCE, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + return JDBCUtils.getLocalDateTimeAsZoned(resultSet, index()); + } + } + : new GenericColumnFetcher<>( + colIndex, columnName, DateTimeType.INSTANCE, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + return JDBCUtils.getZonedDateTime(resultSet, index()); + } + }; default -> new InferredColumnFetcher(colIndex, columnName, problemAggregator); }; } diff --git a/std-bits/google/src/main/java/org/enso/google/CredentialsHelper.java b/std-bits/google/src/main/java/org/enso/google/CredentialsHelper.java index e16d508afdaf..a02ffdf40f1b 100644 --- a/std-bits/google/src/main/java/org/enso/google/CredentialsHelper.java +++ b/std-bits/google/src/main/java/org/enso/google/CredentialsHelper.java @@ -3,9 +3,10 @@ import com.google.auth.oauth2.GoogleCredentials; class CredentialsHelper { - /** Materializes wrapped credentials into the proper object. - *

- * This value should not leak to Enso as it can give the user access to the access token. + /** + * Materializes wrapped credentials into the proper object. + * + *

This value should not leak to Enso as it can give the user access to the access token. */ static GoogleCredentials materialize(WrappedGoogleCredentials wrappedGoogleCredentials) { return switch (wrappedGoogleCredentials) { diff --git a/std-bits/google/src/main/java/org/enso/google/GoogleCredentialsProvider.java b/std-bits/google/src/main/java/org/enso/google/GoogleCredentialsProvider.java index e95b0e109a48..9a5663ec609d 100644 --- a/std-bits/google/src/main/java/org/enso/google/GoogleCredentialsProvider.java +++ b/std-bits/google/src/main/java/org/enso/google/GoogleCredentialsProvider.java @@ -14,9 +14,9 @@ public static GoogleCredentialsProvider fromGoogleCredentials( WrappedGoogleCredentials googleCredentials) { return switch (googleCredentials) { case WrappedGoogleCredentials.SecretCredentials ref -> null; - case WrappedGoogleCredentials.LocalFileCredentials - localCredentials -> new GoogleCredentialsProvider( - FixedCredentialsProvider.create(localCredentials.credential())); + case WrappedGoogleCredentials.LocalFileCredentials localCredentials -> + new GoogleCredentialsProvider( + FixedCredentialsProvider.create(localCredentials.credential())); }; } diff --git a/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/AzureCredential.java b/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/AzureCredential.java index 0d0fc5c35f1d..b957af55e0b9 100644 --- a/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/AzureCredential.java +++ b/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/AzureCredential.java @@ -55,11 +55,10 @@ private static String makeUnique(HideableValue value) { return switch (value) { case HideableValue.PlainValue plainValue -> plainValue.value(); case HideableValue.SecretValue secretID -> "{{Secret:" + secretID.secretId() + "}}"; - case HideableValue.ConcatValues concatValues -> makeUnique(concatValues.left()) - + "_" - + makeUnique(concatValues.right()); - case HideableValue.Base64EncodeValue base64EncodeValue -> "base64_" - + makeUnique(base64EncodeValue.value()); + case HideableValue.ConcatValues concatValues -> + makeUnique(concatValues.left()) + "_" + makeUnique(concatValues.right()); + case HideableValue.Base64EncodeValue base64EncodeValue -> + "base64_" + makeUnique(base64EncodeValue.value()); default -> throw new IllegalArgumentException("Unexpected value: " + value); }; } diff --git a/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/CredentialHelper.java b/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/CredentialHelper.java index 8cd4e97ed203..977a7bed9d8c 100644 --- a/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/CredentialHelper.java +++ b/std-bits/microsoft/src/main/java/org/enso/microsoft/azure/CredentialHelper.java @@ -12,8 +12,8 @@ /** * A helper class to convert {@link AzureCredential} to {@link TokenCredential}. * - *

This class is allowed access to secrets. Extra care should be taken to ensure its result is not - * leaked. + *

This class is allowed access to secrets. Extra care should be taken to ensure its result is + * not leaked. */ final class CredentialHelper { static TokenCredential toTokenCredential(AzureCredential credential) { @@ -24,13 +24,17 @@ static TokenCredential toTokenCredential(AzureCredential credential) { || !isPresent(System.getenv("AZURE_CLIENT_SECRET")) || !isPresent(System.getenv("AZURE_TENANT_ID"))) { throw new ClientAuthenticationException( - "Environment variables AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID are not all set.", + "Environment variables AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID are" + + " not all set.", null); } yield new EnvironmentCredentialBuilder().build(); } case AzureCredential.CLI() -> new AzureCliCredentialBuilder().build(); - case AzureCredential.ClientSecret(HideableValue tenantId, HideableValue clientId, HideableValue clientSecret) -> { + case AzureCredential.ClientSecret( + HideableValue tenantId, + HideableValue clientId, + HideableValue clientSecret) -> { var resolvedTenantId = unsafeResolveSecrets(tenantId); var resolvedClientId = unsafeResolveSecrets(clientId); var resolvedClientSecret = unsafeResolveSecrets(clientSecret); @@ -47,8 +51,8 @@ yield new ClientSecretCredentialBuilder() .build(); } case AzureCredential.BlobStorageSASToken(HideableValue token) -> - throw new ClientAuthenticationException( - "Blob Storage SAS Token is not supported for authentication.", null); + throw new ClientAuthenticationException( + "Blob Storage SAS Token is not supported for authentication.", null); }; } @@ -56,7 +60,8 @@ static String toSASToken(AzureCredential credential) { return switch (credential) { case AzureCredential.BlobStorageSASToken(HideableValue token) -> unsafeResolveSecrets(token); default -> - throw new IllegalArgumentException("Only BlobStorageSASToken credentials can provide a SAS token."); + throw new IllegalArgumentException( + "Only BlobStorageSASToken credentials can provide a SAS token."); }; } diff --git a/std-bits/snowflake/src/main/java/org/enso/snowflake/SnowflakeColumnFetcherFactory.java b/std-bits/snowflake/src/main/java/org/enso/snowflake/SnowflakeColumnFetcherFactory.java index a8447adc365b..48bb8036a9a7 100644 --- a/std-bits/snowflake/src/main/java/org/enso/snowflake/SnowflakeColumnFetcherFactory.java +++ b/std-bits/snowflake/src/main/java/org/enso/snowflake/SnowflakeColumnFetcherFactory.java @@ -57,32 +57,32 @@ public ColumnFetcher forStorageType( // JDBC column indices are 1-based. int colIndex = index + 1; return switch (storageType) { - case TimeOfDayType todt -> new GenericColumnFetcher<>( - colIndex, columnName, todt, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - var timeString = resultSet.getString(index()); - return timeString == null - ? null - : LocalTime.parse(timeString, DateTimeFormatter.ISO_LOCAL_TIME); - } - }; - case DateTimeType dtt -> new GenericColumnFetcher<>( - colIndex, columnName, dtt, problemAggregator) { - @Override - public Object getValue(ResultSet resultSet) throws SQLException { - var timestampString = resultSet.getString(index()); - if (timestampString == null) { - return null; - } + case TimeOfDayType todt -> + new GenericColumnFetcher<>(colIndex, columnName, todt, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + var timeString = resultSet.getString(index()); + return timeString == null + ? null + : LocalTime.parse(timeString, DateTimeFormatter.ISO_LOCAL_TIME); + } + }; + case DateTimeType dtt -> + new GenericColumnFetcher<>(colIndex, columnName, dtt, problemAggregator) { + @Override + public Object getValue(ResultSet resultSet) throws SQLException { + var timestampString = resultSet.getString(index()); + if (timestampString == null) { + return null; + } - var normalised = - timestampString.length() > 10 && timestampString.charAt(10) == 'T' - ? timestampString.substring(0, 10) + ' ' + timestampString.substring(11) - : timestampString; - return Core_Date_Utils.parseZonedDateTime(normalised, DATE_TIME_FORMATTER); - } - }; + var normalised = + timestampString.length() > 10 && timestampString.charAt(10) == 'T' + ? timestampString.substring(0, 10) + ' ' + timestampString.substring(11) + : timestampString; + return Core_Date_Utils.parseZonedDateTime(normalised, DATE_TIME_FORMATTER); + } + }; case BigIntegerType bit -> new SnowflakeIntegerFetcher(colIndex, columnName); default -> super.forStorageType(storageType, index, columnName, problemAggregator); }; diff --git a/std-bits/table/src/main/java/org/enso/table/aggregations/Mean.java b/std-bits/table/src/main/java/org/enso/table/aggregations/Mean.java index b03ecaa33ded..d0251887c339 100644 --- a/std-bits/table/src/main/java/org/enso/table/aggregations/Mean.java +++ b/std-bits/table/src/main/java/org/enso/table/aggregations/Mean.java @@ -40,8 +40,8 @@ private static StorageType resultTypeFromInput(ColumnStorage inputStorage) case BigIntegerType bigIntegerType -> BigDecimalType.INSTANCE; case BigDecimalType bigDecimalType -> BigDecimalType.INSTANCE; case NullType nullType -> nullType; - default -> throw new IllegalStateException( - "Unexpected input type for Mean aggregate: " + inputType); + default -> + throw new IllegalStateException("Unexpected input type for Mean aggregate: " + inputType); }; } @@ -59,8 +59,8 @@ private MeanAccumulator makeAccumulator() { case FloatType floatType -> new FloatMeanAccumulator(); case BigDecimalType bigDecimalType -> new BigDecimalMeanAccumulator(); case NullType nullType -> new NullAccumulator(); - default -> throw new IllegalStateException( - "Unexpected output type in Mean aggregate: " + getType()); + default -> + throw new IllegalStateException("Unexpected output type in Mean aggregate: " + getType()); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/aggregations/Sum.java b/std-bits/table/src/main/java/org/enso/table/aggregations/Sum.java index 3144e62a8654..66090640005a 100644 --- a/std-bits/table/src/main/java/org/enso/table/aggregations/Sum.java +++ b/std-bits/table/src/main/java/org/enso/table/aggregations/Sum.java @@ -37,8 +37,8 @@ public Builder makeBuilder(int size, ProblemAggregator problemAggregator) { case BigIntegerType bigIntegerType -> Builder.getForBigInteger(size, problemAggregator); case FloatType floatType -> Builder.getForDouble(floatType, size, problemAggregator); case NullType nullType -> Builder.getForType(nullType, size, problemAggregator); - default -> throw new IllegalStateException( - "Unexpected input type for Sum aggregate: " + inputType); + default -> + throw new IllegalStateException("Unexpected input type for Sum aggregate: " + inputType); }; } @@ -57,8 +57,8 @@ private SumAccumulator makeAccumulator() { case BigIntegerType bigIntegerType -> new IntegerSumAccumulator(); case FloatType floatType -> new FloatSumAccumulator(); case NullType nullType -> new NullAccumulator(); - default -> throw new IllegalStateException( - "Unexpected input type for Sum aggregate: " + inputType); + default -> + throw new IllegalStateException("Unexpected input type for Sum aggregate: " + inputType); }; } @@ -128,20 +128,22 @@ private void addLong(long value) { case null -> { accumulator = value; } - default -> throw new IllegalStateException( - "Unexpected accumulator type: " + accumulator.getClass()); + default -> + throw new IllegalStateException( + "Unexpected accumulator type: " + accumulator.getClass()); } } private void addBigInteger(BigInteger value) { assert value != null; switch (accumulator) { - case Long accumulatorAsLong -> accumulator = - BigInteger.valueOf(accumulatorAsLong).add(value); + case Long accumulatorAsLong -> + accumulator = BigInteger.valueOf(accumulatorAsLong).add(value); case BigInteger accumulatorAsBigInteger -> accumulator = accumulatorAsBigInteger.add(value); case null -> accumulator = value; - default -> throw new IllegalStateException( - "Unexpected accumulator type: " + accumulator.getClass()); + default -> + throw new IllegalStateException( + "Unexpected accumulator type: " + accumulator.getClass()); } } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/DataQualityMetrics.java b/std-bits/table/src/main/java/org/enso/table/data/column/DataQualityMetrics.java index 18a148293515..5f9f9f4c6ccc 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/DataQualityMetrics.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/DataQualityMetrics.java @@ -143,22 +143,25 @@ private static DataQualityMetrics createMetrics(ColumnStorage columnStorage) return switch (resolvedStorage.getType()) { case NullType nullType -> new NullQualityMetrics(resolvedStorage); case TextType textType -> new StringQualityMetrics(textType.asTypedStorage(resolvedStorage)); - case FloatType floatType -> NumericQualityMetrics.forDouble( - floatType.asTypedStorage(resolvedStorage)); - case IntegerType integerType -> NumericQualityMetrics.forLong( - integerType.asTypedStorage(resolvedStorage)); - case BigIntegerType bigIntegerType -> NumericQualityMetrics.forBigInteger( - bigIntegerType.asTypedStorage(resolvedStorage)); - case BigDecimalType bigDecimalType -> NumericQualityMetrics.forBigDecimal( - bigDecimalType.asTypedStorage(resolvedStorage)); - case DateType dateType -> new MinMaxQualityMetrics<>( - dateType.asTypedStorage(resolvedStorage), LocalDate::compareTo); - case TimeOfDayType timeType -> new MinMaxQualityMetrics<>( - timeType.asTypedStorage(resolvedStorage), LocalTime::compareTo); - case DateTimeType dateTimeType -> new MinMaxQualityMetrics<>( - dateTimeType.asTypedStorage(resolvedStorage), ZonedDateTime::compareTo); - case AnyObjectType anyObjectType -> new AnyObjectQualityMetric( - anyObjectType.asTypedStorage(resolvedStorage)); + case FloatType floatType -> + NumericQualityMetrics.forDouble(floatType.asTypedStorage(resolvedStorage)); + case IntegerType integerType -> + NumericQualityMetrics.forLong(integerType.asTypedStorage(resolvedStorage)); + case BigIntegerType bigIntegerType -> + NumericQualityMetrics.forBigInteger(bigIntegerType.asTypedStorage(resolvedStorage)); + case BigDecimalType bigDecimalType -> + NumericQualityMetrics.forBigDecimal(bigDecimalType.asTypedStorage(resolvedStorage)); + case DateType dateType -> + new MinMaxQualityMetrics<>( + dateType.asTypedStorage(resolvedStorage), LocalDate::compareTo); + case TimeOfDayType timeType -> + new MinMaxQualityMetrics<>( + timeType.asTypedStorage(resolvedStorage), LocalTime::compareTo); + case DateTimeType dateTimeType -> + new MinMaxQualityMetrics<>( + dateTimeType.asTypedStorage(resolvedStorage), ZonedDateTime::compareTo); + case AnyObjectType anyObjectType -> + new AnyObjectQualityMetric(anyObjectType.asTypedStorage(resolvedStorage)); default -> new BaseQualityMetrics(resolvedStorage); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/builder/Builder.java b/std-bits/table/src/main/java/org/enso/table/data/column/builder/Builder.java index 31a52cbc6d83..1177f2845b25 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/builder/Builder.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/builder/Builder.java @@ -54,8 +54,8 @@ static ColumnStorage fromRepeatedItem(Object item, long size) { // Create a single storage item based on the type of the item. return switch (item) { case null -> new NullBuilder().appendNulls(checkSize(size)).seal(); - case Boolean booleanValue -> new BoolStorage( - new BitSet(), new BitSet(), checkSize(size), booleanValue); + case Boolean booleanValue -> + new BoolStorage(new BitSet(), new BitSet(), checkSize(size), booleanValue); default -> { var storageType = StorageType.forBoxedItem(item, PreciseTypeOptions.DEFAULT); var builder = Builder.getForType(storageType, size, BlackholeProblemAggregator.INSTANCE); @@ -106,10 +106,11 @@ static Builder getForType(StorageType type, long size, ProblemAggregator prob case BigIntegerType t -> getForBigInteger(size, problemAggregator); case NullType t -> new NullBuilder(); case null -> getInferredBuilder(size, problemAggregator); - default -> getForType( - StorageType.fromTypeCharAndSize(type.typeChar(), type.size()), - size, - problemAggregator); + default -> + getForType( + StorageType.fromTypeCharAndSize(type.typeChar(), type.size()), + size, + problemAggregator); }; assert Objects.equals(builder.getType(), type); diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/BinaryCoalescingOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/BinaryCoalescingOperation.java index 8b6af12f916d..327ceec8cd60 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/BinaryCoalescingOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/BinaryCoalescingOperation.java @@ -102,8 +102,9 @@ public static Column min( case TimeOfDayType t -> TIME_MIN; case TextType t -> TEXT_MIN; case BooleanType b -> BinaryCoalescingOperationBool.MIN_INSTANCE; - case NumericType n -> BinaryCoalescingOperationNumeric.create( - leftStorage.getType(), right, BinaryCoalescingOperationNumeric.MIN_OPERATION); + case NumericType n -> + BinaryCoalescingOperationNumeric.create( + leftStorage.getType(), right, BinaryCoalescingOperationNumeric.MIN_OPERATION); default -> null; }; return applyOperation( @@ -144,8 +145,9 @@ public static Column max( case TimeOfDayType t -> TIME_MAX; case TextType t -> TEXT_MAX; case BooleanType b -> BinaryCoalescingOperationBool.MAX_INSTANCE; - case NumericType n -> BinaryCoalescingOperationNumeric.create( - leftStorage.getType(), right, BinaryCoalescingOperationNumeric.MAX_OPERATION); + case NumericType n -> + BinaryCoalescingOperationNumeric.create( + leftStorage.getType(), right, BinaryCoalescingOperationNumeric.MAX_OPERATION); default -> null; }; return applyOperation( diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/IsInOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/IsInOperation.java index dbb410929123..55901ae62c7d 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/IsInOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/IsInOperation.java @@ -1,15 +1,20 @@ package org.enso.table.data.column.operation; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.BitSet; +import java.util.HashSet; +import java.util.List; +import java.util.function.BiPredicate; +import java.util.function.Function; import org.enso.base.polyglot.NumericConverter; import org.enso.table.data.column.builder.Builder; +import org.enso.table.data.column.operation.unary.NotOperation; import org.enso.table.data.column.storage.BoolStorage; import org.enso.table.data.column.storage.ColumnBooleanStorage; import org.enso.table.data.column.storage.ColumnStorage; import org.enso.table.data.column.storage.ColumnStorageWithInferredStorage; import org.enso.table.data.column.storage.ColumnStorageWithNothingMap; -import org.enso.table.data.table.problems.MapOperationProblemAggregator; -import org.enso.table.data.column.operation.unary.NotOperation; - import org.enso.table.data.column.storage.type.AnyObjectType; import org.enso.table.data.column.storage.type.BigDecimalType; import org.enso.table.data.column.storage.type.BigIntegerType; @@ -22,18 +27,11 @@ import org.enso.table.data.column.storage.type.TextType; import org.enso.table.data.column.storage.type.TimeOfDayType; import org.enso.table.data.table.Column; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.BitSet; -import java.util.HashSet; -import java.util.List; -import java.util.function.BiPredicate; -import java.util.function.Function; +import org.enso.table.data.table.problems.MapOperationProblemAggregator; /** - * The IsInOperation class provides a way to check if a value is in a set of values. - * It checks if the condition is valid. + * The IsInOperation class provides a way to check if a value is in a set of values. It checks if + * the condition is valid. */ public final class IsInOperation { /** @@ -58,10 +56,7 @@ public static boolean isSupported(Column column) { * @return a new column with the results of the operation */ public static Column apply( - Column left, - String new_name, - Object arg, - MapOperationProblemAggregator problemAggregator) { + Column left, String new_name, Object arg, MapOperationProblemAggregator problemAggregator) { if (arg instanceof Column argColumn) { return apply(left, new_name, argColumn.asList(), problemAggregator); } @@ -75,26 +70,55 @@ public static Column apply( } var leftStorage = ColumnStorageWithInferredStorage.resolveStorage(left); - var result = switch (leftStorage.getType()) { - case NullType nt -> Builder.makeEmpty(BooleanType.INSTANCE, leftStorage.getSize()); - case BooleanType bt -> applyBooleanIsIn(bt.asTypedStorage(leftStorage), list, problemAggregator); - case DateType dt -> applySpecialized(dt.asTypedStorage(leftStorage), list, dt::valueAsType, problemAggregator); - case DateTimeType dtt -> applySpecialized(dtt.asTypedStorage(leftStorage), list, dtt::valueAsType, problemAggregator); - case TimeOfDayType todt -> applySpecialized(todt.asTypedStorage(leftStorage), list, todt::valueAsType, problemAggregator); - case TextType tt -> applySpecialized(tt.asTypedStorage(leftStorage), list, tt::valueAsType, problemAggregator); - case IntegerType it -> applySpecialized(it.asTypedStorage(leftStorage), list, NumericConverter::tryConvertingToLong, problemAggregator); - case FloatType ft -> applySpecialized(ft.asTypedStorage(leftStorage), list, NumericConverter::tryConvertingToDouble, problemAggregator); - case BigIntegerType bit -> applySpecialized(bit.asTypedStorage(leftStorage), list, bit::valueAsType, problemAggregator); - case BigDecimalType bdt -> applySpecialized(bdt.asTypedStorage(leftStorage), list, o -> tryConvertingToBigDecimal(o, problemAggregator), problemAggregator, IsInOperation::containsBigDecimal); - default -> - throw new IllegalArgumentException( - "Unsupported StorageType for `is_in`: " + leftStorage.getType()); - }; + var result = + switch (leftStorage.getType()) { + case NullType nt -> Builder.makeEmpty(BooleanType.INSTANCE, leftStorage.getSize()); + case BooleanType bt -> + applyBooleanIsIn(bt.asTypedStorage(leftStorage), list, problemAggregator); + case DateType dt -> + applySpecialized( + dt.asTypedStorage(leftStorage), list, dt::valueAsType, problemAggregator); + case DateTimeType dtt -> + applySpecialized( + dtt.asTypedStorage(leftStorage), list, dtt::valueAsType, problemAggregator); + case TimeOfDayType todt -> + applySpecialized( + todt.asTypedStorage(leftStorage), list, todt::valueAsType, problemAggregator); + case TextType tt -> + applySpecialized( + tt.asTypedStorage(leftStorage), list, tt::valueAsType, problemAggregator); + case IntegerType it -> + applySpecialized( + it.asTypedStorage(leftStorage), + list, + NumericConverter::tryConvertingToLong, + problemAggregator); + case FloatType ft -> + applySpecialized( + ft.asTypedStorage(leftStorage), + list, + NumericConverter::tryConvertingToDouble, + problemAggregator); + case BigIntegerType bit -> + applySpecialized( + bit.asTypedStorage(leftStorage), list, bit::valueAsType, problemAggregator); + case BigDecimalType bdt -> + applySpecialized( + bdt.asTypedStorage(leftStorage), + list, + o -> tryConvertingToBigDecimal(o, problemAggregator), + problemAggregator, + IsInOperation::containsBigDecimal); + default -> + throw new IllegalArgumentException( + "Unsupported StorageType for `is_in`: " + leftStorage.getType()); + }; return new Column(new_name, result); } - private static BigDecimal tryConvertingToBigDecimal(Object o, MapOperationProblemAggregator problemAggregator) { + private static BigDecimal tryConvertingToBigDecimal( + Object o, MapOperationProblemAggregator problemAggregator) { return switch (o) { case BigDecimal x -> x; case BigInteger x -> new BigDecimal(x); @@ -125,7 +149,10 @@ private static boolean containsBigDecimal(HashSet set, BigDecimal bi * elements for faster contains checks. */ private record CompactRepresentation(HashSet uniqueValues, boolean hadNull) { - public static CompactRepresentation create(List arg, Function converter, MapOperationProblemAggregator problemAggregator) { + public static CompactRepresentation create( + List arg, + Function converter, + MapOperationProblemAggregator problemAggregator) { boolean hadNull = false; boolean hadFloat = false; var uniqueValues = new HashSet(); @@ -157,12 +184,12 @@ private static ColumnStorage applySpecialized( return applySpecialized(storage, arg, converter, problemAggregator, HashSet::contains); } - private static ColumnStorage applySpecialized( - ColumnStorage storage, - List arg, - Function converter, - MapOperationProblemAggregator problemAggregator, - BiPredicate, T> contains) { + private static ColumnStorage applySpecialized( + ColumnStorage storage, + List arg, + Function converter, + MapOperationProblemAggregator problemAggregator, + BiPredicate, T> contains) { // Convert the List to a Set var result = CompactRepresentation.create(arg, converter, problemAggregator); @@ -219,7 +246,10 @@ public static BooleanFlags of(List arg) { } } - private static ColumnStorage applyBooleanIsIn(ColumnBooleanStorage boolStorage, List arg, MapOperationProblemAggregator problemAggregator) { + private static ColumnStorage applyBooleanIsIn( + ColumnBooleanStorage boolStorage, + List arg, + MapOperationProblemAggregator problemAggregator) { // Process arg into flags for true, false, and null var flags = BooleanFlags.of(arg); @@ -263,15 +293,18 @@ private static ColumnStorage applyBooleanIsIn(ColumnBooleanStorage boolStorag }); } - private static ColumnStorage applyBoolStorage(boolean keepValue, BoolStorage boolStorage, int checkedSize) { + private static ColumnStorage applyBoolStorage( + boolean keepValue, BoolStorage boolStorage, int checkedSize) { BitSet values = boolStorage.getValues(); BitSet isNothing = boolStorage.getIsNothingMap(); if (keepValue) { - var newIsNothing = boolStorage.isNegated() ? or(isNothing, values) : orNot(isNothing, values, checkedSize); + var newIsNothing = + boolStorage.isNegated() ? or(isNothing, values) : orNot(isNothing, values, checkedSize); return new BoolStorage(values, newIsNothing, checkedSize, boolStorage.isNegated()); } else { - var newIsNothing = boolStorage.isNegated() ? orNot(isNothing, values, checkedSize) : or(isNothing, values); + var newIsNothing = + boolStorage.isNegated() ? orNot(isNothing, values, checkedSize) : or(isNothing, values); return new BoolStorage(values, newIsNothing, checkedSize, !boolStorage.isNegated()); } } @@ -291,7 +324,7 @@ private static BitSet makeIsNothingMap(ColumnStorage storage, int size) { } private static BitSet or(BitSet left, BitSet right) { - BitSet result = (BitSet)left.clone(); + BitSet result = (BitSet) left.clone(); result.or(right); return result; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/JsonOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/JsonOperation.java index 6d9ea4c900ed..7e28c6580ed6 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/JsonOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/JsonOperation.java @@ -41,12 +41,12 @@ public static String apply( return switch (fullStorage.getType()) { case NullType nullType -> createNullJson(length); - case BooleanType booleanType -> createBooleanJson( - booleanType.asTypedStorage(fullStorage), start, length); - case IntegerType integerType -> createIntegerJson( - integerType.asTypedStorage(fullStorage), start, length); - case FloatType floatType -> createFloatJson( - floatType.asTypedStorage(fullStorage), start, length); + case BooleanType booleanType -> + createBooleanJson(booleanType.asTypedStorage(fullStorage), start, length); + case IntegerType integerType -> + createIntegerJson(integerType.asTypedStorage(fullStorage), start, length); + case FloatType floatType -> + createFloatJson(floatType.asTypedStorage(fullStorage), start, length); default -> createObjectJson(fullStorage, start, length, ensoJsonCallback); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/NumericColumnAdapter.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/NumericColumnAdapter.java index 468f690bccd2..046c7674a2e9 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/NumericColumnAdapter.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/NumericColumnAdapter.java @@ -63,14 +63,16 @@ public StorageType[] getValidInputs() { public ColumnStorage asTypedStorage(ColumnStorage storage) { return switch (storage.getType()) { case FloatType floatType -> floatType.asTypedStorage(storage); - case BigDecimalType bigDecimalType -> new DoubleStorageFacade<>( - bigDecimalType.asTypedStorage(storage), BigDecimal::doubleValue); - case BigIntegerType bigIntegerType -> new DoubleStorageFacade<>( - bigIntegerType.asTypedStorage(storage), BigInteger::doubleValue); - case IntegerType integerType -> new DoubleStorageFacade<>( - integerType.asTypedStorage(storage), Long::doubleValue); - default -> throw new IllegalArgumentException( - "Unsupported storage type: " + storage.getType()); + case BigDecimalType bigDecimalType -> + new DoubleStorageFacade<>( + bigDecimalType.asTypedStorage(storage), BigDecimal::doubleValue); + case BigIntegerType bigIntegerType -> + new DoubleStorageFacade<>( + bigIntegerType.asTypedStorage(storage), BigInteger::doubleValue); + case IntegerType integerType -> + new DoubleStorageFacade<>(integerType.asTypedStorage(storage), Long::doubleValue); + default -> + throw new IllegalArgumentException("Unsupported storage type: " + storage.getType()); }; } @@ -158,14 +160,14 @@ public StorageType[] getValidInputs() { public ColumnStorage asTypedStorage(ColumnStorage storage) { return switch (storage.getType()) { case BigDecimalType bigDecimalType -> bigDecimalType.asTypedStorage(storage); - case BigIntegerType bigIntegerType -> new ColumnStorageFacade<>( - bigIntegerType.asTypedStorage(storage), BigDecimal::new); - case FloatType floatType -> new ColumnStorageFacade<>( - floatType.asTypedStorage(storage), BigDecimal::valueOf); - case IntegerType integerType -> new ColumnStorageFacade<>( - integerType.asTypedStorage(storage), BigDecimal::valueOf); - default -> throw new IllegalArgumentException( - "Unsupported storage type: " + storage.getType()); + case BigIntegerType bigIntegerType -> + new ColumnStorageFacade<>(bigIntegerType.asTypedStorage(storage), BigDecimal::new); + case FloatType floatType -> + new ColumnStorageFacade<>(floatType.asTypedStorage(storage), BigDecimal::valueOf); + case IntegerType integerType -> + new ColumnStorageFacade<>(integerType.asTypedStorage(storage), BigDecimal::valueOf); + default -> + throw new IllegalArgumentException("Unsupported storage type: " + storage.getType()); }; } } @@ -189,10 +191,10 @@ public StorageType[] getValidInputs() { public ColumnStorage asTypedStorage(ColumnStorage storage) { return switch (storage.getType()) { case BigIntegerType bigIntegerType -> bigIntegerType.asTypedStorage(storage); - case IntegerType integerType -> new ColumnStorageFacade<>( - integerType.asTypedStorage(storage), BigInteger::valueOf); - default -> throw new IllegalArgumentException( - "Unsupported storage type: " + storage.getType()); + case IntegerType integerType -> + new ColumnStorageFacade<>(integerType.asTypedStorage(storage), BigInteger::valueOf); + default -> + throw new IllegalArgumentException("Unsupported storage type: " + storage.getType()); }; } } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/UnaryOperationNumeric.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/UnaryOperationNumeric.java index 03b978c8a76a..27849dc18b21 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/UnaryOperationNumeric.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/UnaryOperationNumeric.java @@ -54,10 +54,10 @@ public ColumnStorage apply( } return switch (storage) { - case ColumnLongStorage longStorage -> innerApplySpecializedLongStorage( - longStorage, problemAggregator); - case ColumnDoubleStorage doubleStorage -> innerApplySpecializedDoubleStorage( - doubleStorage, problemAggregator); + case ColumnLongStorage longStorage -> + innerApplySpecializedLongStorage(longStorage, problemAggregator); + case ColumnDoubleStorage doubleStorage -> + innerApplySpecializedDoubleStorage(doubleStorage, problemAggregator); default -> innerApply(adapter.asTypedStorage(storage), problemAggregator); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/cast/CastOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/cast/CastOperation.java index 4276fce6a1ce..04bffb8d9517 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/cast/CastOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/cast/CastOperation.java @@ -51,8 +51,9 @@ private static StorageConverter fromStorageType(StorageType storageType) { case BigIntegerType bigIntegerType -> new ToBigIntegerConverter(); case BigDecimalType bigDecimalType -> new ToBigDecimalConverter(); case NullType nullType -> throw new IllegalArgumentException("Cannot cast to Null type."); - default -> fromStorageType( - StorageType.fromTypeCharAndSize(storageType.typeChar(), storageType.size())); + default -> + fromStorageType( + StorageType.fromTypeCharAndSize(storageType.typeChar(), storageType.size())); }; } @@ -426,16 +427,19 @@ public static long maxPrecisionStored(Column column) { var accumulator = new PrecisionAccumulator(); switch (storage.getType()) { - case BigDecimalType bigDecimalType -> StorageIterators.forEachOverStorage( - bigDecimalType.asTypedStorage(storage), - "maxPrecisionStored:BigDecimal", - (index, item) -> accumulator.accumulate(item)); - case BigIntegerType bigIntegerType -> StorageIterators.forEachOverStorage( - bigIntegerType.asTypedStorage(storage), - "maxPrecisionStored:BigInteger", - (index, item) -> accumulator.accumulate(new BigDecimal(item))); - default -> throw new IllegalArgumentException( - "Cannot compute max precision for storage type: " + storage.getType()); + case BigDecimalType bigDecimalType -> + StorageIterators.forEachOverStorage( + bigDecimalType.asTypedStorage(storage), + "maxPrecisionStored:BigDecimal", + (index, item) -> accumulator.accumulate(item)); + case BigIntegerType bigIntegerType -> + StorageIterators.forEachOverStorage( + bigIntegerType.asTypedStorage(storage), + "maxPrecisionStored:BigInteger", + (index, item) -> accumulator.accumulate(new BigDecimal(item))); + default -> + throw new IllegalArgumentException( + "Cannot compute max precision for storage type: " + storage.getType()); } return accumulator.getMaxPrecision(); diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/comparators/Comparators.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/comparators/Comparators.java index 53a8d15384a8..310ce0415c1d 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/comparators/Comparators.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/comparators/Comparators.java @@ -38,8 +38,9 @@ public static BinaryOperationTyped eq(Column left, Object right) { case TimeOfDayType tm -> TimeOfDayComparators.EQ; case TextType tt -> StringComparators.EQ; case BooleanType bt -> BooleanComparators.EQ; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.EQUAL_OPERATION, false); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.EQUAL_OPERATION, false); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } @@ -53,8 +54,9 @@ public static BinaryOperationTyped notEq(Column left, Object right) { case TimeOfDayType tm -> TimeOfDayComparators.NEQ; case TextType tt -> StringComparators.NEQ; case BooleanType bt -> BooleanComparators.NEQ; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.NOT_EQUAL_OPERATION, true); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.NOT_EQUAL_OPERATION, true); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } @@ -68,8 +70,9 @@ public static BinaryOperationTyped lessThan(Column left, Object right) case TimeOfDayType tm -> TimeOfDayComparators.LT; case TextType tt -> StringComparators.LT; case BooleanType bt -> BooleanComparators.LT; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.LESS_OPERATION); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.LESS_OPERATION); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } @@ -83,8 +86,9 @@ public static BinaryOperationTyped lessThanEq(Column left, Object right case TimeOfDayType tm -> TimeOfDayComparators.LTE; case TextType tt -> StringComparators.LTE; case BooleanType bt -> BooleanComparators.LTE; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.LESS_OR_EQUAL_OPERATION); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.LESS_OR_EQUAL_OPERATION); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } @@ -98,8 +102,9 @@ public static BinaryOperationTyped greaterThan(Column left, Object righ case TimeOfDayType tm -> TimeOfDayComparators.GT; case TextType tt -> StringComparators.GT; case BooleanType bt -> BooleanComparators.GT; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.GREATER_OPERATION); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.GREATER_OPERATION); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } @@ -113,8 +118,9 @@ public static BinaryOperationTyped greaterThanEq(Column left, Object ri case TimeOfDayType tm -> TimeOfDayComparators.GTE; case TextType tt -> StringComparators.GTE; case BooleanType bt -> BooleanComparators.GTE; - case NumericType nt -> NumericComparators.create( - leftStorage.getType(), right, NumericComparators.GREATER_OR_EQUAL_OPERATION); + case NumericType nt -> + NumericComparators.create( + leftStorage.getType(), right, NumericComparators.GREATER_OR_EQUAL_OPERATION); default -> throw new IllegalArgumentException("Unsupported StorageType"); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/masks/MaskOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/masks/MaskOperation.java index c9ba7eeec22d..0f3c338f00e4 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/masks/MaskOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/masks/MaskOperation.java @@ -57,22 +57,26 @@ public static Column mask(Column column, long[] mask) { public static ColumnStorage getSlicedStorage( ColumnStorage storage, IndexMapper indexMapper) { return switch (storage) { - case MaskedStorageLong sliceStorageLong -> new MaskedStorageLong( - sliceStorageLong.parent(), sliceStorageLong.indexMapper().merge(indexMapper)); + case MaskedStorageLong sliceStorageLong -> + new MaskedStorageLong( + sliceStorageLong.parent(), sliceStorageLong.indexMapper().merge(indexMapper)); case ColumnLongStorage longStorage -> new MaskedStorageLong(longStorage, indexMapper); - case MaskedStorageDouble sliceStorageDouble -> new MaskedStorageDouble( - sliceStorageDouble.parent(), sliceStorageDouble.indexMapper().merge(indexMapper)); + case MaskedStorageDouble sliceStorageDouble -> + new MaskedStorageDouble( + sliceStorageDouble.parent(), sliceStorageDouble.indexMapper().merge(indexMapper)); case ColumnDoubleStorage doubleStorage -> new MaskedStorageDouble(doubleStorage, indexMapper); - case MaskedStorageBoolean sliceStorageBoolean -> new MaskedStorageBoolean( - sliceStorageBoolean.parent(), sliceStorageBoolean.indexMapper().merge(indexMapper)); - case ColumnBooleanStorage booleanStorage -> new MaskedStorageBoolean( - booleanStorage, indexMapper); - case MaskedStorageInferred sliceStorageInferred -> new MaskedStorageInferred<>( - sliceStorageInferred.parent(), sliceStorageInferred.indexMapper().merge(indexMapper)); - case ColumnStorageWithInferredStorage inferredStorage -> new MaskedStorageInferred<>( - storage, indexMapper); - case MaskedStorage sliceStorage -> new MaskedStorage<>( - sliceStorage.parent(), sliceStorage.indexMapper().merge(indexMapper)); + case MaskedStorageBoolean sliceStorageBoolean -> + new MaskedStorageBoolean( + sliceStorageBoolean.parent(), sliceStorageBoolean.indexMapper().merge(indexMapper)); + case ColumnBooleanStorage booleanStorage -> + new MaskedStorageBoolean(booleanStorage, indexMapper); + case MaskedStorageInferred sliceStorageInferred -> + new MaskedStorageInferred<>( + sliceStorageInferred.parent(), sliceStorageInferred.indexMapper().merge(indexMapper)); + case ColumnStorageWithInferredStorage inferredStorage -> + new MaskedStorageInferred<>(storage, indexMapper); + case MaskedStorage sliceStorage -> + new MaskedStorage<>(sliceStorage.parent(), sliceStorage.indexMapper().merge(indexMapper)); default -> new MaskedStorage<>(storage, indexMapper); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/NotOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/NotOperation.java index ad01b58e2760..0af21a0f5a93 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/NotOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/NotOperation.java @@ -37,17 +37,18 @@ public ColumnStorage apply( return switch (storage) { case BoolStorage boolStorage -> applySpecializedBoolStorage(boolStorage); case ColumnBooleanStorage columnBooleanStorage -> applyOverBooleans(columnBooleanStorage); - default -> StorageIterators.buildOverStorage( - storage, - Builder.getForBoolean(storage.getSize()), - (builder, index, value) -> { - if (value instanceof Boolean b) { - builder.appendBoolean(!b); - } else { - throw new IllegalArgumentException( - "Unsupported type: " + value.getClass() + " (expected boolean type)."); - } - }); + default -> + StorageIterators.buildOverStorage( + storage, + Builder.getForBoolean(storage.getSize()), + (builder, index, value) -> { + if (value instanceof Boolean b) { + builder.appendBoolean(!b); + } else { + throw new IllegalArgumentException( + "Unsupported type: " + value.getClass() + " (expected boolean type)."); + } + }); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/RoundOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/RoundOperation.java index 789b1c4f20f9..ecd84ca0ba22 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/RoundOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/RoundOperation.java @@ -103,42 +103,48 @@ public static UnaryOperation create(Column left, long decimalPlacesLong, boolean int decimalPlaces = Math.toIntExact(decimalPlacesLong); var storage = ColumnStorageWithInferredStorage.resolveStorage(left); return switch (storage.getType()) { - case NullType nt -> decimalPlaces <= 0 - ? new RoundOperation<>( - NumericColumnAdapter.DoubleColumnAdapter.INSTANCE, - true, - IntegerType.INT_64, - v -> null) - : new RoundOperation<>( - NumericColumnAdapter.DoubleColumnAdapter.INSTANCE, - true, - FloatType.FLOAT_64, - v -> null); - case BigDecimalType bd -> decimalPlaces <= 0 - ? new RoundOperation<>( - NumericColumnAdapter.BigDecimalColumnAdapter.INSTANCE, - false, - BigIntegerType.INSTANCE, - roundBigDecimalToBigInteger(decimalPlaces, useBankers)) - : new RoundOperation<>( - NumericColumnAdapter.BigDecimalColumnAdapter.INSTANCE, - false, - BigDecimalType.INSTANCE, - roundBigDecimal(decimalPlaces, useBankers)); - case BigIntegerType bi -> decimalPlaces >= 0 - ? UnaryOperation.IDENTITY - : new RoundOperation<>( - NumericColumnAdapter.BigIntegerColumnAdapter.INSTANCE, - BigIntegerType.INSTANCE, - roundBigInteger(decimalPlaces, useBankers)); - case IntegerType lt -> decimalPlaces >= 0 - ? UnaryOperation.IDENTITY - : createForLong(lt, roundLong(decimalPlaces, useBankers)); - case FloatType ft -> decimalPlaces <= 0 - ? createForDouble(IntegerType.INT_64, roundDoubleToLong(decimalPlaces, useBankers)) - : createForDouble(FloatType.FLOAT_64, roundDouble(decimalPlaces, useBankers)); - default -> throw new UnsupportedOperationException( - "Unsupported storage type for round operation: " + storage.getType()); + case NullType nt -> + decimalPlaces <= 0 + ? new RoundOperation<>( + NumericColumnAdapter.DoubleColumnAdapter.INSTANCE, + true, + IntegerType.INT_64, + v -> null) + : new RoundOperation<>( + NumericColumnAdapter.DoubleColumnAdapter.INSTANCE, + true, + FloatType.FLOAT_64, + v -> null); + case BigDecimalType bd -> + decimalPlaces <= 0 + ? new RoundOperation<>( + NumericColumnAdapter.BigDecimalColumnAdapter.INSTANCE, + false, + BigIntegerType.INSTANCE, + roundBigDecimalToBigInteger(decimalPlaces, useBankers)) + : new RoundOperation<>( + NumericColumnAdapter.BigDecimalColumnAdapter.INSTANCE, + false, + BigDecimalType.INSTANCE, + roundBigDecimal(decimalPlaces, useBankers)); + case BigIntegerType bi -> + decimalPlaces >= 0 + ? UnaryOperation.IDENTITY + : new RoundOperation<>( + NumericColumnAdapter.BigIntegerColumnAdapter.INSTANCE, + BigIntegerType.INSTANCE, + roundBigInteger(decimalPlaces, useBankers)); + case IntegerType lt -> + decimalPlaces >= 0 + ? UnaryOperation.IDENTITY + : createForLong(lt, roundLong(decimalPlaces, useBankers)); + case FloatType ft -> + decimalPlaces <= 0 + ? createForDouble(IntegerType.INT_64, roundDoubleToLong(decimalPlaces, useBankers)) + : createForDouble(FloatType.FLOAT_64, roundDouble(decimalPlaces, useBankers)); + default -> + throw new UnsupportedOperationException( + "Unsupported storage type for round operation: " + storage.getType()); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/UnaryRoundOperation.java b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/UnaryRoundOperation.java index f7a880339205..bc4f38ea1871 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/UnaryRoundOperation.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/operation/unary/UnaryRoundOperation.java @@ -99,8 +99,9 @@ private void applyObject( case Float f -> applyDouble(builder, f, problemAggregator); case BigDecimal bd -> builder.append(bigDecimalFunction.apply(bd)); case Number n -> applyDouble(builder, n.doubleValue(), problemAggregator); - default -> throw new IllegalArgumentException( - "Unsupported type: " + value.getClass() + " (expected numeric type)."); + default -> + throw new IllegalArgumentException( + "Unsupported type: " + value.getClass() + " (expected numeric type)."); } } } diff --git a/std-bits/table/src/main/java/org/enso/table/data/column/storage/type/StorageType.java b/std-bits/table/src/main/java/org/enso/table/data/column/storage/type/StorageType.java index 9999408bbb62..aebc1e1fa74a 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/column/storage/type/StorageType.java +++ b/std-bits/table/src/main/java/org/enso/table/data/column/storage/type/StorageType.java @@ -136,13 +136,14 @@ static StorageType fromTypeCharAndSize(char typeChar, long size) { } yield FloatType.FLOAT_64; } - case 'I' -> switch ((int) size) { - case 8 -> IntegerType.INT_8; - case 16 -> IntegerType.INT_16; - case 32 -> IntegerType.INT_32; - case 64 -> IntegerType.INT_64; - default -> throw new IllegalArgumentException("Unknown integer size: " + size); - }; + case 'I' -> + switch ((int) size) { + case 8 -> IntegerType.INT_8; + case 16 -> IntegerType.INT_16; + case 32 -> IntegerType.INT_32; + case 64 -> IntegerType.INT_64; + default -> throw new IllegalArgumentException("Unknown integer size: " + size); + }; case 'N' -> NullType.INSTANCE; case 'S' -> size == -1 ? TextType.VARIABLE_LENGTH : TextType.variableLengthWithLimit(size); case 'T' -> TextType.fixedLength(size); diff --git a/std-bits/table/src/main/java/org/enso/table/data/table/Column.java b/std-bits/table/src/main/java/org/enso/table/data/table/Column.java index 17a66f899a51..c726269b34f1 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/table/Column.java +++ b/std-bits/table/src/main/java/org/enso/table/data/table/Column.java @@ -42,9 +42,8 @@ public static void ensureNameIsValid(String name) { switch (name) { case null -> "Column name cannot be Nothing."; case "" -> "Column name cannot be empty."; - default -> (name.indexOf('\0') >= 0) - ? "Column name cannot contain the NUL character." - : null; + default -> + (name.indexOf('\0') >= 0) ? "Column name cannot contain the NUL character." : null; }; throw new InvalidColumnNameException(name, extraMessage); } diff --git a/std-bits/table/src/main/java/org/enso/table/data/table/join/lookup/LookupJoin.java b/std-bits/table/src/main/java/org/enso/table/data/table/join/lookup/LookupJoin.java index 0158a3b73f0a..da994e4d4149 100644 --- a/std-bits/table/src/main/java/org/enso/table/data/table/join/lookup/LookupJoin.java +++ b/std-bits/table/src/main/java/org/enso/table/data/table/join/lookup/LookupJoin.java @@ -151,8 +151,8 @@ private long findLookupRow(long baseRowIx) { private LookupOutputColumn prepareOutputColumn(LookupColumnDescription description) { return switch (description) { - case LookupColumnDescription.KeepOriginal keepOriginal -> new LookupOutputColumn.KeepOriginal( - keepOriginal.column()); + case LookupColumnDescription.KeepOriginal keepOriginal -> + new LookupOutputColumn.KeepOriginal(keepOriginal.column()); case LookupColumnDescription.MergeColumns mergeColumns -> { String name = mergeColumns.original().getName(); if (allowUnmatchedRows) { @@ -169,8 +169,8 @@ private LookupOutputColumn prepareOutputColumn(LookupColumnDescription descripti yield new LookupOutputColumn.AddFromLookup(renamedLookup); } } - case LookupColumnDescription.AddNew addNew -> new LookupOutputColumn.AddFromLookup( - addNew.lookupColumn()); + case LookupColumnDescription.AddNew addNew -> + new LookupOutputColumn.AddFromLookup(addNew.lookupColumn()); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/excel/ExcelConnectionPool.java b/std-bits/table/src/main/java/org/enso/table/excel/ExcelConnectionPool.java index d70ceb1de9d8..dd78f8b02ebb 100644 --- a/std-bits/table/src/main/java/org/enso/table/excel/ExcelConnectionPool.java +++ b/std-bits/table/src/main/java/org/enso/table/excel/ExcelConnectionPool.java @@ -124,8 +124,8 @@ public R writeWorkbook(File file, Function writeAction) throws // Ignore: Workaround for bug https://bz.apache.org/bugzilla/show_bug.cgi?id=59252 } } - default -> throw new IllegalStateException( - "Unknown workbook type: " + workbook.getClass()); + default -> + throw new IllegalStateException("Unknown workbook type: " + workbook.getClass()); } } else { try (OutputStream fileOut = Files.newOutputStream(file.toPath())) { diff --git a/std-bits/table/src/main/java/org/enso/table/excel/ExcelHeaders.java b/std-bits/table/src/main/java/org/enso/table/excel/ExcelHeaders.java index b7f4ca4cda62..730881396893 100644 --- a/std-bits/table/src/main/java/org/enso/table/excel/ExcelHeaders.java +++ b/std-bits/table/src/main/java/org/enso/table/excel/ExcelHeaders.java @@ -23,8 +23,8 @@ public ExcelHeaders( names = switch (headers) { case EXCEL_COLUMN_NAMES -> null; - case USE_FIRST_ROW_AS_HEADERS -> readRowAsHeaders( - startRow, startCol, endCol, deduplicator); + case USE_FIRST_ROW_AS_HEADERS -> + readRowAsHeaders(startRow, startCol, endCol, deduplicator); case INFER -> inferHeaders(startRow, nextRow, startCol, endCol, deduplicator); }; } diff --git a/std-bits/table/src/main/java/org/enso/table/excel/ExcelRow.java b/std-bits/table/src/main/java/org/enso/table/excel/ExcelRow.java index f77c2eae533e..bab77b451771 100644 --- a/std-bits/table/src/main/java/org/enso/table/excel/ExcelRow.java +++ b/std-bits/table/src/main/java/org/enso/table/excel/ExcelRow.java @@ -144,8 +144,8 @@ public String getCellText(int column) { return switch (cellType) { case ERROR -> - // Want to show the error message rather than empty. - FormulaError.forInt(cell.getErrorCellValue()).getString(); + // Want to show the error message rather than empty. + FormulaError.forInt(cell.getErrorCellValue()).getString(); case NUMERIC -> { // Special handling for Number or Date cells as want to keep formatting. var format = ExcelNumberFormat.from(cell, null); diff --git a/std-bits/table/src/main/java/org/enso/table/excel/ExcelUtils.java b/std-bits/table/src/main/java/org/enso/table/excel/ExcelUtils.java index 851fee7aeb63..4a68c1c36461 100644 --- a/std-bits/table/src/main/java/org/enso/table/excel/ExcelUtils.java +++ b/std-bits/table/src/main/java/org/enso/table/excel/ExcelUtils.java @@ -98,8 +98,8 @@ public static Temporal fromExcelDateTime1904(double value) { public static double toExcelDateTime(Temporal temporal) { return switch (temporal) { case ZonedDateTime zonedDateTime -> toExcelDateTime(zonedDateTime.toLocalDateTime()); - case LocalDateTime dateTime -> toExcelDateTime(dateTime.toLocalDate()) - + toExcelDateTime(dateTime.toLocalTime()); + case LocalDateTime dateTime -> + toExcelDateTime(dateTime.toLocalDate()) + toExcelDateTime(dateTime.toLocalTime()); case LocalDate date -> { long days = ChronoUnit.DAYS.between(EPOCH_1900, date); @@ -119,8 +119,8 @@ public static double toExcelDateTime(Temporal temporal) { yield days; } case LocalTime time -> time.toNanoOfDay() / 1000000.0 / MILLIS_PER_DAY; - default -> throw new IllegalArgumentException( - "Unsupported Temporal type: " + temporal.getClass()); + default -> + throw new IllegalArgumentException("Unsupported Temporal type: " + temporal.getClass()); }; } @@ -128,12 +128,12 @@ public static double toExcelDateTime(Temporal temporal) { public static double toExcelDateTime1904(Temporal temporal) { return switch (temporal) { case ZonedDateTime zonedDateTime -> toExcelDateTime1904(zonedDateTime.toLocalDateTime()); - case LocalDateTime dateTime -> toExcelDateTime1904(dateTime.toLocalDate()) - + toExcelDateTime1904(dateTime.toLocalTime()); + case LocalDateTime dateTime -> + toExcelDateTime1904(dateTime.toLocalDate()) + toExcelDateTime1904(dateTime.toLocalTime()); case LocalDate date -> ChronoUnit.DAYS.between(EPOCH_1904, date); case LocalTime time -> time.toNanoOfDay() / 1000000.0 / MILLIS_PER_DAY; - default -> throw new IllegalArgumentException( - "Unsupported Temporal type: " + temporal.getClass()); + default -> + throw new IllegalArgumentException("Unsupported Temporal type: " + temporal.getClass()); }; } } diff --git a/std-bits/table/src/main/java/org/enso/table/write/ExcelWriter.java b/std-bits/table/src/main/java/org/enso/table/write/ExcelWriter.java index 05e433d2d95b..83dc771b3235 100644 --- a/std-bits/table/src/main/java/org/enso/table/write/ExcelWriter.java +++ b/std-bits/table/src/main/java/org/enso/table/write/ExcelWriter.java @@ -271,8 +271,8 @@ private static void appendRangeWithTable( InterruptedException { Table mappedTable = switch (existingDataMode) { - case APPEND_BY_INDEX -> ColumnMapper.mapColumnsByPosition( - table, expanded.getColumnCount()); + case APPEND_BY_INDEX -> + ColumnMapper.mapColumnsByPosition(table, expanded.getColumnCount()); case APPEND_BY_NAME -> { if (headers == ExcelHeaders.HeaderBehavior.EXCEL_COLUMN_NAMES) { throw new IllegalArgumentException( @@ -285,10 +285,11 @@ private static void appendRangeWithTable( yield ColumnMapper.mapColumnsByName( table, NameDeduplicator.createIgnoringProblems().makeUniqueArray(currentHeaders)); } - default -> throw new IllegalArgumentException( - "Internal Error: appendRangeWithTable called with illegal existing data mode '" - + existingDataMode - + "'."); + default -> + throw new IllegalArgumentException( + "Internal Error: appendRangeWithTable called with illegal existing data mode '" + + existingDataMode + + "'."); }; if (range.isSingleCell()) { diff --git a/std-bits/tableau/src/main/java/org/enso/tableau/HyperFormat.java b/std-bits/tableau/src/main/java/org/enso/tableau/HyperFormat.java index 9107171c81f5..44ff2bc092a5 100644 --- a/std-bits/tableau/src/main/java/org/enso/tableau/HyperFormat.java +++ b/std-bits/tableau/src/main/java/org/enso/tableau/HyperFormat.java @@ -73,8 +73,8 @@ private static String getHyperPath() { } else { return switch (OSPlatform.CurrentPlatform) { case WINDOWS -> System.getenv("LocalAppData") + "/enso/hyper"; - case MAC_ARM64, MAX_X64 -> System.getProperty("user.home") - + "/Library/Application Support/org.enso/hyper"; + case MAC_ARM64, MAX_X64 -> + System.getProperty("user.home") + "/Library/Application Support/org.enso/hyper"; case LINUX, OTHER -> System.getProperty("user.home") + "/.local/share/enso/hyper"; }; } @@ -94,24 +94,28 @@ private static HyperProcess getProcess() throws IOException { try (var files = Files.list(HYPER_PATH)) { if (files.findAny().isEmpty()) { switch (OSPlatform.CurrentPlatform) { - case WINDOWS -> downloadHyper( - "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/hyperd.exe", - "hyperd.exe", - false); - case MAC_ARM64 -> downloadHyper( - "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/macos-arm64/hyperd", - "hyperd", - true); - case MAX_X64 -> downloadHyper( - "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/macos-x64/hyperd", - "hyperd", - true); - case LINUX -> downloadHyper( - "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/linux/hyperd", - "hyperd", - true); - case OTHER -> throw new IOException( - "Unsupported platform: " + OSPlatform.CurrentPlatform); + case WINDOWS -> + downloadHyper( + "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/hyperd.exe", + "hyperd.exe", + false); + case MAC_ARM64 -> + downloadHyper( + "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/macos-arm64/hyperd", + "hyperd", + true); + case MAX_X64 -> + downloadHyper( + "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/macos-x64/hyperd", + "hyperd", + true); + case LINUX -> + downloadHyper( + "https://enso-data-samples.s3.us-west-1.amazonaws.com/tableau/linux/hyperd", + "hyperd", + true); + case OTHER -> + throw new IOException("Unsupported platform: " + OSPlatform.CurrentPlatform); } } } catch (IOException @@ -404,12 +408,12 @@ private static SqlType mapEnsoTypeToSqlType(StorageType type) { case DateType t -> SqlType.date(); case TimeOfDayType t -> SqlType.time(); case DateTimeType t -> SqlType.timestampTz(); - // https://tableau.github.io/hyper-db/docs/sql/datatype/numeric - // Precisions over 18 require 128-bit for internal storage. Processing 128-bit numeric - // values is often slower than processing 64-bit values, so it is advisable to use - // a sensible precision for the use case at hand instead of always using the maximum - // precision by default. - // TODO fix this after https://github.com/enso-org/enso/issues/13022 + // https://tableau.github.io/hyper-db/docs/sql/datatype/numeric + // Precisions over 18 require 128-bit for internal storage. Processing 128-bit numeric + // values is often slower than processing 64-bit values, so it is advisable to use + // a sensible precision for the use case at hand instead of always using the maximum + // precision by default. + // TODO fix this after https://github.com/enso-org/enso/issues/13022 case BigDecimalType t -> SqlType.numeric(18, 9); default -> throw new HyperUnsupportedTypeError(type.toString()); }; diff --git a/tools/http-test-helper/src/main/java/org/enso/shttp/cloud_mock/CloudAuthRenew.java b/tools/http-test-helper/src/main/java/org/enso/shttp/cloud_mock/CloudAuthRenew.java index 3a8c91e906b5..adf7ee85dc6f 100644 --- a/tools/http-test-helper/src/main/java/org/enso/shttp/cloud_mock/CloudAuthRenew.java +++ b/tools/http-test-helper/src/main/java/org/enso/shttp/cloud_mock/CloudAuthRenew.java @@ -1,6 +1,5 @@ package org.enso.shttp.cloud_mock; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; @@ -41,7 +40,8 @@ private void sendRenewedToken(HttpExchange exchange) throws IOException { } private void sendMalformedResponse(HttpExchange exchange) throws IOException { - var response = new MalformedRenewResponse(new MalformedAuthenticationResult("foobar", 123, 3600)); + var response = + new MalformedRenewResponse(new MalformedAuthenticationResult("foobar", 123, 3600)); sendResponse(200, jsonMapper.writeValueAsString(response), exchange); }