From 38a2da7754fea821063a45c5f9468be78742bf7e Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 25 Mar 2022 12:03:05 +0100 Subject: [PATCH 01/73] Dynamically replace builtin methods with functions This is WIP. This change does not attempt to handle @Builtin_Type. Yet. During the initialization of Builtins we collect info about root nodes representing generated AST truffle nodes. Such nodes will dynamically replace implementations of @Builtin_Method stubs during IR to Truffle translation. There are still rough edges to work out but checking this in to see if this is the direction we want to take. --- build.sbt | 3 +- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 90 +++++++++++++++++++ docs/runtime-roadmap.md | 2 +- .../interpreter/runtime/builtin/Builtins.java | 68 +++++++++++++- .../interpreter/runtime/builtin/Polyglot.java | 46 ---------- .../runtime/scope/ModuleScope.java | 3 +- .../runtime/src/main/resources/Builtins.enso | 87 +----------------- .../enso/compiler/codegen/IrToTruffle.scala | 17 +++- .../compiler/pass/lint/UnusedBindings.scala | 1 + .../src/Semantic/Python_Interop_Spec.enso | 2 + 10 files changed, 178 insertions(+), 141 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Polyglot.java diff --git a/build.sbt b/build.sbt index 217832da9d05..e5c50a3ae80b 100644 --- a/build.sbt +++ b/build.sbt @@ -1147,7 +1147,8 @@ lazy val runtime = (project in file("engine/runtime")) "org.scalatest" %% "scalatest" % scalatestVersion % Test, "org.graalvm.truffle" % "truffle-api" % graalVersion % Benchmark, "org.typelevel" %% "cats-core" % catsVersion, - "eu.timepit" %% "refined" % refinedVersion + "eu.timepit" %% "refined" % refinedVersion, + "org.reflections" % "reflections" % "0.10.2" ), // Note [Unmanaged Classpath] Compile / unmanagedClasspath += (`core-definition` / Compile / packageBin).value, diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso new file mode 100644 index 000000000000..546d3c7a5c11 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -0,0 +1,90 @@ +## Reads the number of elements in a given polyglot array object. + + Arguments: + - array: a polyglot array object, originating in any supported language. +get_array_size : Any -> Integer +get_array_size array = @Builtin_Method "Polyglot.get_array_size" + +## Executes a polyglot function object (e.g. a lambda). + + Arguments: + - callable: The polyglot function object to execute. + - arguments: A vector of arguments to callable. +execute : Any -> Vector -> Any +execute callable arguments = @Builtin_Method "Polyglot.execute" + +## Performs a by-name lookup for a member in a polyglot object. + + Arguments: + - object: The polyglot object on which to perform the member lookup. + - member_name: The textual name of the member to lookup. + + > Example + Look up the field a on an object o. + Polyglot.get_member o "a" +get_member : Any -> Text +get_member object member_name = @Builtin_Method "Polyglot.get_member" + +## Returns a polyglot array of all of the members of the provided object. + + Arguments: + - object: The object from which to get a list of member names. + + > Example + Get a list of the fields for an object o. + + Polyglot.get_members o +get_members : Any -> Array +get_members object = @Builtin_Method "Polyglot.get_members" + +## Instantiates a polyglot object using the provided constructor. + + Arguments: + - constructor: The constructor with which to instantiate the object. + - arguments: A vector of the arguments to pass to the polyglot + constructor. + + > Example + Instantiate a new Java Integer with the value 1. + + Polyglot.new Integer [1] +new : Any -> Vector -> Any +new constructor arguments = @Builtin_Method "Polglot.new" + +## Invokes a method on a polyglot object by name. + + Arguments: + - target: The polyglot object on which to call the method. + - name: The name of the method. + - arguments: The arguments to pass to the method given by name. +invoke : Any -> Text -> Vector -> Any +invoke target name arguments = @Builtin_Method "Polyglot.invoke" + +## ADVANCED + UNSTABLE + + Checks if `value` defines a source location. + + Source locations are typically exposed by functions, classes, sometimes + also other objects to specify their allocation sites. +has_source_location : Any -> Boolean +has_source_location value = @Builtin_Method "Polyglot.has_source_location" + +## ADVANCED + UNSTABLE + + Gets the source location of `value`. + + Source locations are typically exposed by functions, classes, sometimes + also other objects to specify their allocation sites. + This method will throw a polyglot exception if + `Polyglot.has_source_location value` returns `False`. +get_source_location : Any -> Source_Location +get_source_location value = @Builtin_Method "Polyglot.get_source_location" + +## Checks if a polyglot language is installed in the runtime environment. + + Arguments: + - langauge_name: The name of the language to test +is_language_installed : Text -> Bool +is_language_installed language_name = @Builtin_Method "Polyglot.is_language_installed" diff --git a/docs/runtime-roadmap.md b/docs/runtime-roadmap.md index 4b598c38ef16..13fd82207c14 100644 --- a/docs/runtime-roadmap.md +++ b/docs/runtime-roadmap.md @@ -217,7 +217,7 @@ Enso has a concept of _extension methods_. These are methods that are _not_ defined "alongside" the type (in the same compilation unit). Currently, we have no way to define methods that are _not_ extensions on builtin types without defining them in Java. This is awkward, and leads to a poor experience for both -developers of Enso, and the users (where there is a special case rule rule for +developers of Enso, and the users (where there is a special case rule for certain types, and also a hacky form of documentation for these same types). For types defined in Java, their methods defined in Enso are extensions and are diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index ea3dcccfe0ec..da9490243c42 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -2,13 +2,17 @@ import com.oracle.truffle.api.CompilerDirectives; import java.io.IOException; +import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; -import java.util.Objects; +import java.util.*; + +import com.oracle.truffle.api.nodes.NodeInfo; import org.enso.compiler.Passes; import org.enso.compiler.context.FreshNameSupply; import org.enso.compiler.exception.CompilerError; import org.enso.compiler.phase.BuiltinsIrBuilder; import org.enso.interpreter.Language; +import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; import org.enso.interpreter.node.expression.builtin.error.CatchAnyMethodGen; @@ -17,6 +21,8 @@ import org.enso.interpreter.node.expression.builtin.error.GetAttachedStackTraceMethodGen; import org.enso.interpreter.node.expression.builtin.error.ThrowPanicMethodGen; import org.enso.interpreter.node.expression.builtin.function.ExplicitCallFunctionMethodGen; +import org.enso.interpreter.node.expression.builtin.interop.generic.GetMemberMethodGen; +import org.enso.interpreter.node.expression.builtin.interop.generic.IsLanguageInstalledMethodGen; import org.enso.interpreter.node.expression.builtin.interop.java.AddToClassPathMethodGen; import org.enso.interpreter.node.expression.builtin.interop.java.LookupClassMethodGen; import org.enso.interpreter.node.expression.builtin.io.GetCwdMethodGen; @@ -41,10 +47,14 @@ import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.Constants; import org.enso.pkg.QualifiedName; +import org.reflections.Reflections; +import org.reflections.scanners.Scanners; + /** Container class for static predefined atoms, methods, and their containing scope. */ public class Builtins { public static final String PACKAGE_NAME = "Builtins"; @@ -59,6 +69,8 @@ public static class Debug { } } + private HashMap>> builtinNodes; + private final AtomConstructor any; private final AtomConstructor debug; private final AtomConstructor projectDescription; @@ -76,7 +88,7 @@ public static class Debug { private final Mutable mutable; private final Number number; private final Ordering ordering; - private final Polyglot polyglot; + private final AtomConstructor polyglot; private final Resource resource; private final System system; private final Text text; @@ -91,6 +103,7 @@ public Builtins(Context context) { Language language = context.getLanguage(); module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); scope = module.compileScope(context); + builtinNodes = new HashMap<>(); any = new AtomConstructor("Any", scope).initializeFields(); bool = new Bool(language, scope); @@ -117,7 +130,9 @@ public Builtins(Context context) { new ArgumentDefinition(0, "payload", ArgumentDefinition.ExecutionMode.EXECUTE), new ArgumentDefinition( 1, "internal_original_exception", ArgumentDefinition.ExecutionMode.EXECUTE)); - polyglot = new Polyglot(language, scope); + // TODO remove once @Builtin_Type is handled + polyglot = new AtomConstructor("Polyglot", scope).initializeFields(); + scope.registerConstructor(polyglot); resource = new Resource(language, scope); system = new System(language, scope); text = new Text(language, scope); @@ -200,6 +215,7 @@ public Builtins(Context context) { thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); + readAllBuiltinNodes(); } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ @@ -240,6 +256,50 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } } + @CompilerDirectives.TruffleBoundary + public void readAllBuiltinNodes() { + try { + Reflections reflections = new Reflections("org.enso.interpreter.node.expression.builtin"); + Set subtypes = reflections.get(Scanners.SubTypes.of(Scanners.TypesAnnotated.with(NodeInfo.class))); + subtypes.stream().forEach(className -> { + try { + Class clazz = (Class) Class.forName(className); + NodeInfo info = clazz.getDeclaredAnnotation(NodeInfo.class); + String[] name = info.shortName().split("\\."); + if (name.length == 2 && !name[0].isEmpty()) { + Map> atomNodes = builtinNodes.get(name[0]); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + builtinNodes.put(name[0], atomNodes); + } + atomNodes.put(name[1], clazz); + } + } catch (Exception e) { + e.printStackTrace(); + } + // todo: handle gracefully other cases + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Optional getBuiltinFunction(String atomName, String methodName, Language language) { + Map> atomNodes = builtinNodes.get(atomName); + if (atomNodes == null) + return Optional.empty(); + Class clazz = atomNodes.get(methodName); + if (clazz == null) + return Optional.empty(); + try { + Method meth = clazz.getMethod("makeFunction", Language.class); + return Optional.ofNullable((Function) meth.invoke(null, language)); + } catch (Exception e) { + e.printStackTrace(); + return Optional.empty(); + } + } + /** * Returns the {@code Nothing} atom constructor. * @@ -320,7 +380,7 @@ public Mutable mutable() { } /** @return the container for polyglot-related builtins. */ - public Polyglot polyglot() { + public AtomConstructor polyglot() { return polyglot; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Polyglot.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Polyglot.java deleted file mode 100644 index 633033d6578d..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Polyglot.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.interop.generic.*; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** A container class for all Polyglot-related stdlib builtins. */ -public class Polyglot { - - private final AtomConstructor polyglot; - - /** - * Creates and registers all polyglot-related functions and types. - * - * @param language the current language instance. - * @param scope the builtin scope. - */ - public Polyglot(Language language, ModuleScope scope) { - this.polyglot = new AtomConstructor("Polyglot", scope).initializeFields(); - createPolyglot(language, scope); - } - - private void createPolyglot(Language language, ModuleScope scope) { - scope.registerConstructor(polyglot); - scope.registerMethod(polyglot, "execute", ExecuteMethodGen.makeFunction(language)); - scope.registerMethod(polyglot, "invoke", InvokeMethodGen.makeFunction(language)); - scope.registerMethod(polyglot, "new", InstantiateMethodGen.makeFunction(language)); - scope.registerMethod(polyglot, "get_member", GetMemberMethodGen.makeFunction(language)); - scope.registerMethod(polyglot, "get_members", GetMembersMethodGen.makeFunction(language)); - scope.registerMethod(polyglot, "get_array_size", GetArraySizeMethodGen.makeFunction(language)); - scope.registerMethod( - polyglot, "is_language_installed", IsLanguageInstalledMethodGen.makeFunction(language)); - scope.registerMethod( - polyglot, "get_executable_name", GetExecutableNameMethodGen.makeFunction(language)); - scope.registerMethod( - polyglot, "get_source_location", GetSourceLocationMethodGen.makeFunction(language)); - scope.registerMethod( - polyglot, "has_source_location", HasSourceLocationMethodGen.makeFunction(language)); - } - - /** @return the atom constructor for polyglot */ - public AtomConstructor getPolyglot() { - return polyglot; - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 965624314f3d..b349960d91d5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -7,6 +7,7 @@ import com.oracle.truffle.api.interop.TruffleObject; import org.enso.interpreter.runtime.Module; +import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.error.RedefinedMethodException; @@ -129,8 +130,6 @@ public void registerMethod(AtomConstructor atom, String method, Function functio * @return a list containing all the defined conversions in definition order */ private Map ensureConversionsFor(AtomConstructor cons) { - //var methods = ensureMethodMapFor(cons); - //methods. return conversions.computeIfAbsent(cons, k -> new HashMap<>()); } diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 371258b02925..3541ee470adc 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -493,93 +493,10 @@ type Polyglot Polyglot is a term that refers to other languages (such as Java) that are running on the same JVM. + @Builtin_Type type Polyglot - ## Reads the number of elements in a given polyglot array object. - - Arguments: - - array: a polyglot array object, originating in any supported language. - get_array_size : Any -> Integer - get_array_size array = @Builtin_Method "Polyglot.get_array_size" - - ## Executes a polyglot function object (e.g. a lambda). - - Arguments: - - callable: The polyglot function object to execute. - - arguments: A vector of arguments to callable. - execute : Any -> Vector -> Any - execute callable arguments = @Builtin_Method "Polyglot.execute" - - ## Performs a by-name lookup for a member in a polyglot object. - - Arguments: - - object: The polyglot object on which to perform the member lookup. - - member_name: The textual name of the member to lookup. - - > Example - Look up the field a on an object o. - Polyglot.get_member o "a" - get_member : Any -> Text - get_member object member_name = @Builtin_Method "Polyglot.get_member" - - ## Returns a polyglot array of all of the members of the provided object. - - Arguments: - - object: The object from which to get a list of member names. - - > Example - Get a list of the fields for an object o. - - Polyglot.get_members o - get_members : Any -> Array - get_members object = @Builtin_Method "Polyglot.get_members" - - ## Instantiates a polyglot object using the provided constructor. - - Arguments: - - constructor: The constructor with which to instantiate the object. - - arguments: A vector of the arguments to pass to the polyglot - constructor. - - > Example - Instantiate a new Java Integer with the value 1. - - Polyglot.new Integer [1] - new : Any -> Vector -> Any - new constructor arguments = @Builtin_Method "Polglot.new" - - ## Invokes a method on a polyglot object by name. - - Arguments: - - target: The polyglot object on which to call the method. - - name: The name of the method. - - arguments: The arguments to pass to the method given by name. - invoke : Any -> Text -> Vector -> Any - invoke target name arguments = @Builtin_Method "Polyglot.invoke" - - ## ADVANCED - UNSTABLE - - Checks if `value` defines a source location. - - Source locations are typically exposed by functions, classes, sometimes - also other objects to specify their allocation sites. - has_source_location : Any -> Boolean - has_source_location value = @Builtin_Method "Polyglot.has_source_location" - - ## ADVANCED - UNSTABLE - - Gets the source location of `value`. - - Source locations are typically exposed by functions, classes, sometimes - also other objects to specify their allocation sites. - This method will throw a polyglot exception if - `Polyglot.has_source_location value` returns `False`. - get_source_location : Any -> Source_Location - get_source_location value = @Builtin_Method "Polyglot.get_source_location" - ## Utilities for working with Java polyglot objects. type Java @@ -1073,7 +990,7 @@ type Ref > Example Storing the value 10 in a reference. - Ref.put (Ref.new 0) 7 + Ref.put (Ref.new 0) 10 put : Ref -> Any -> Any put ref new_value = @Builtin_Method "Ref.put" diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index e832f1a6985e..75409fd97872 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -12,7 +12,7 @@ import org.enso.compiler.pass.analyse.AliasAnalysis.Graph.{Scope => AliasScope} import org.enso.compiler.pass.analyse.AliasAnalysis.{Graph => AliasGraph} import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis, DataflowAnalysis, TailCall} import org.enso.compiler.pass.optimise.ApplicationSaturation -import org.enso.compiler.pass.resolve.{MethodDefinitions, Patterns, UppercaseNames} +import org.enso.compiler.pass.resolve.{ExpressionAnnotations, MethodDefinitions, Patterns, UppercaseNames} import org.enso.interpreter.epb.EpbParser import org.enso.interpreter.node.callable.argument.ReadArgumentNode import org.enso.interpreter.node.callable.function.{BlockNode, CreateFunctionNode} @@ -243,6 +243,9 @@ class IrToTruffle( ) val function = methodDef.body match { + case fn: IR.Function if isBuiltin(fn.body) => + val builtinFunction = context.getBuiltins.getBuiltinFunction(cons.getName(), methodDef.methodName.name, language); + builtinFunction.orElseThrow() case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) @@ -328,6 +331,16 @@ class IrToTruffle( }) } + private def isBuiltin(expression: IR.Expression): Boolean = { + expression + .getMetadata(ExpressionAnnotations) + .exists(anns => + anns.annotations.exists(a => + a.name == ExpressionAnnotations.builtinMethodName + ) + ) + } + // ========================================================================== // === Utility Functions ==================================================== // ========================================================================== @@ -781,7 +794,7 @@ class IrToTruffle( val array = context.getBuiltins.mutable.array val bool = context.getBuiltins.bool val number = context.getBuiltins.number - val polyglot = context.getBuiltins.polyglot.getPolyglot + val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text val branchNode: BranchNode = if (atomCons == bool.getTrue) { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala index 986d2e56f138..1f44a273d93d 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala @@ -110,6 +110,7 @@ case object UnusedBindings extends IRPass { .unsafeAs[AliasAnalysis.Info.Occurrence] val isUsed = aliasInfo.graph.linksFor(aliasInfo.id).nonEmpty + // FIXME: take into account @Builtin_Method if (!isIgnored && !isUsed) { binding .copy(expression = runExpression(binding.expression, context)) diff --git a/test/Tests/src/Semantic/Python_Interop_Spec.enso b/test/Tests/src/Semantic/Python_Interop_Spec.enso index 95c20ad8286b..d891452a5696 100644 --- a/test/Tests/src/Semantic/Python_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Python_Interop_Spec.enso @@ -166,3 +166,5 @@ spec = error = Error.throw 42 here.my_method error 0 . should_fail_with Integer +main = Test.Suite.run_main here.spec + From 374a94cffce1d7f3f296d16662875d400f03d2bf Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 29 Mar 2022 15:36:02 +0200 Subject: [PATCH 02/73] Deal with Polyglot split by selectively importing Sadly because of the move of the functions to a separate module and @Builtin_Type Polyglot still being in Builtins it's tricky to get auto imports that don't require manual adjustments. The main issue is with `PolyglotBranchNode` in `IrToTruffle` that requires a reference to the polyglot atom constructor. Decided to make this incremental step to do some benchmarking of @Builtin_Method solution and then move on @Builtin_Type. The latter will require a separate pass, hence the additional step. Additionally removed unused warnings for methods annotated with @Builtin_Method. --- .../Base/0.0.0-dev/src/Data/Vector.enso | 4 +- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 69 ++++++++++--------- .../0.0.0-dev/src/Runtime/Extensions.enso | 6 +- .../Base/0.0.0-dev/src/System/File.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Warning.enso | 6 +- .../enso/compiler/codegen/IrToTruffle.scala | 27 ++++---- .../scala/org/enso/compiler/core/IR.scala | 10 +++ .../compiler/pass/lint/UnusedBindings.scala | 34 +++++++-- .../test/semantic/PolyglotTest.scala | 6 +- test/Tests/src/Semantic/Case_Spec.enso | 10 +-- test/Tests/src/Semantic/Meta_Spec.enso | 5 +- 13 files changed, 115 insertions(+), 70 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso index 1842b46eaf03..2d18b0902713 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso @@ -89,7 +89,7 @@ new_builder = Builder.new If this didn't happen then it would be possible for the underlying array to be mutated under the hood, and sneak mutability into our immutable data. from_array : Any -> Vector.Vector Any -from_array arr = here.new (Polyglot.get_array_size arr) (arr.at _) +from_array arr = here.new (Base.Polyglot.get_array_size arr) (arr.at _) ## The basic, immutable, vector type. type Vector @@ -121,7 +121,7 @@ type Vector [1, 2, 3, 4].length length : Number - length = Polyglot.get_array_size this.to_array + length = Base.Polyglot.get_array_size this.to_array ## Gets an element from the vector at a specified index (0-based). diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 20300da37da3..ba258d2b2a32 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -20,6 +20,7 @@ import project.Error.Extensions import project.Math import project.Meta import project.Meta.Enso_Project +import project.Polyglot import project.Polyglot.Java import project.Runtime.Extensions import project.System.Environment @@ -39,6 +40,7 @@ export project.Data.Ordering.Sort_Order export project.Data.Vector export project.Math export project.Meta +export project.Polyglot export project.System.Environment export project.System.File export project.Data.Text.Regex.Mode as Regex_Mode @@ -66,5 +68,5 @@ from project.Meta.Enso_Project export all from project.Polyglot.Java export all from project.Runtime.Extensions export all -from Standard.Builtins export all hiding Meta, Less, Equal, Greater, Ordering +from Standard.Builtins export all hiding Meta, Less, Equal, Greater, Ordering, Polyglot diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso index 52919c6bfcc9..5892676afcb4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso @@ -86,7 +86,7 @@ is_a value typ = if typ == Any then True else Number -> if typ == Number then True else case value of Integer -> typ == Integer Decimal -> typ == Decimal - Base.Polyglot -> typ == Base.Polyglot + Builtins.Polyglot -> typ == Builtins.Polyglot _ -> meta_val = here.meta value case meta_val of diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso index 546d3c7a5c11..cc26d4ee40d4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -15,76 +15,81 @@ execute callable arguments = @Builtin_Method "Polyglot.execute" ## Performs a by-name lookup for a member in a polyglot object. - Arguments: - - object: The polyglot object on which to perform the member lookup. - - member_name: The textual name of the member to lookup. + Arguments: + - object: The polyglot object on which to perform the member lookup. + - member_name: The textual name of the member to lookup. - > Example - Look up the field a on an object o. - Polyglot.get_member o "a" + > Example + Look up the field a on an object o. + Polyglot.get_member o "a" get_member : Any -> Text get_member object member_name = @Builtin_Method "Polyglot.get_member" ## Returns a polyglot array of all of the members of the provided object. - Arguments: - - object: The object from which to get a list of member names. - - > Example - Get a list of the fields for an object o. + Arguments: + - object: The object from which to get a list of member names. - Polyglot.get_members o + > Example + Get a list of the fields for an object o. + Polyglot.get_members o get_members : Any -> Array get_members object = @Builtin_Method "Polyglot.get_members" ## Instantiates a polyglot object using the provided constructor. - Arguments: - - constructor: The constructor with which to instantiate the object. - - arguments: A vector of the arguments to pass to the polyglot + Arguments: + - constructor: The constructor with which to instantiate the object. + - arguments: A vector of the arguments to pass to the polyglot constructor. - > Example + > Example Instantiate a new Java Integer with the value 1. - Polyglot.new Integer [1] new : Any -> Vector -> Any -new constructor arguments = @Builtin_Method "Polglot.new" +new constructor arguments = @Builtin_Method "Polyglot.new" ## Invokes a method on a polyglot object by name. - Arguments: - - target: The polyglot object on which to call the method. - - name: The name of the method. - - arguments: The arguments to pass to the method given by name. + Arguments: + - target: The polyglot object on which to call the method. + - name: The name of the method. + - arguments: The arguments to pass to the method given by name. invoke : Any -> Text -> Vector -> Any invoke target name arguments = @Builtin_Method "Polyglot.invoke" ## ADVANCED UNSTABLE - Checks if `value` defines a source location. + Checks if `value` defines a source location. - Source locations are typically exposed by functions, classes, sometimes - also other objects to specify their allocation sites. + Source locations are typically exposed by functions, classes, sometimes + also other objects to specify their allocation sites. has_source_location : Any -> Boolean has_source_location value = @Builtin_Method "Polyglot.has_source_location" ## ADVANCED UNSTABLE - Gets the source location of `value`. + Gets the source location of `value`. - Source locations are typically exposed by functions, classes, sometimes - also other objects to specify their allocation sites. - This method will throw a polyglot exception if - `Polyglot.has_source_location value` returns `False`. + Source locations are typically exposed by functions, classes, sometimes + also other objects to specify their allocation sites. + This method will throw a polyglot exception if + `Polyglot.has_source_location value` returns `False`. get_source_location : Any -> Source_Location get_source_location value = @Builtin_Method "Polyglot.get_source_location" ## Checks if a polyglot language is installed in the runtime environment. - Arguments: - - langauge_name: The name of the language to test + Arguments: + - langauge_name: The name of the language to test is_language_installed : Text -> Bool is_language_installed language_name = @Builtin_Method "Polyglot.is_language_installed" + +## ADVANCED + UNSTABLE + + Returns the executable name of a polyglot object. +get_executable_name : Any -> Text +get_executable_name = @Builtin_Method "Polyglot.get_executable_name" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso index 083fab6d8f6f..c2f2f395bc13 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso @@ -90,8 +90,8 @@ Runtime.get_stack_trace = ## PRIVATE Converts a primitive stack trace element into the regular one. wrap_primitive_stack_trace_element el = - loc = case Polyglot.has_source_location el of - True -> Source_Location (Polyglot.get_source_location el) + loc = case Base.Polyglot.has_source_location el of + True -> Source_Location (Base.Polyglot.get_source_location el) False -> Nothing - name = Polyglot.get_executable_name el + name = Base.Polyglot.get_executable_name el Stack_Trace_Element name loc diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso index d2ec6ac6f410..2d7055385fb2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso @@ -867,7 +867,7 @@ type File_Error list_immediate_children : File -> Vector.Vector File list_immediate_children directory = arr = directory.prim_file.list - Vector.new (Polyglot.get_array_size arr) ix-> + Vector.new (Base.Polyglot.get_array_size arr) ix-> File (arr.at ix) ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso index 6c51a4f2bfd4..44d7af345437 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso @@ -39,10 +39,10 @@ type Warning reassignments : Vector.Vector Stack_Trace_Element reassignments = Vector.Vector (Prim_Warning.get_reassignments this.prim_warning) . map r-> - loc = case Polyglot.has_source_location r of + loc = case Base.Polyglot.has_source_location r of False -> Nothing - True -> Source_Location (Polyglot.get_source_location r) - Stack_Trace_Element (Polyglot.get_executable_name r) loc + True -> Source_Location (Base.Polyglot.get_source_location r) + Stack_Trace_Element (Base.Polyglot.get_executable_name r) loc ## UNSTABLE diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 75409fd97872..2ad2a6d0553a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -243,9 +243,9 @@ class IrToTruffle( ) val function = methodDef.body match { - case fn: IR.Function if isBuiltin(fn.body) => - val builtinFunction = context.getBuiltins.getBuiltinFunction(cons.getName(), methodDef.methodName.name, language); - builtinFunction.orElseThrow() + case fn: IR.Function if isBuiltinMethod(fn.body) => + val builtinFunction = context.getBuiltins.getBuiltinFunction(cons.getName(), methodDef.methodName.name, language) + builtinFunction.orElseThrow(() => new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) @@ -331,20 +331,21 @@ class IrToTruffle( }) } - private def isBuiltin(expression: IR.Expression): Boolean = { - expression - .getMetadata(ExpressionAnnotations) - .exists(anns => - anns.annotations.exists(a => - a.name == ExpressionAnnotations.builtinMethodName - ) - ) - } - // ========================================================================== // === Utility Functions ==================================================== // ========================================================================== + /** Checks if the expression has a @Builtin_Method annotation + * + * @param expression the expression to check + * @return 'true' if 'expression' has @Builtin_Method annotation, otherwise 'false' + */ + private def isBuiltinMethod(expression: IR.Expression): Boolean = { + expression + .getMetadata(ExpressionAnnotations) + .exists(_.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName)) + } + /** Creates a source section from a given location in the code. * * @param location the location to turn into a section diff --git a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala index 8f6f49d8c940..bdf9c7beab7a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala @@ -6369,6 +6369,16 @@ object IR { "A @Tail_Call annotation was placed in a non-tail-call position." } + /** A warning about a `@Builtin_Method` annotation placed in a method + * with unexpected body. + * @param location the location of the annotated application + */ + case class WrongBuiltinMethod(override val location: Option[IdentifiedLocation]) + extends Warning { + override def message: String = + "A @Builtin_Method annotation allows only the name of the builtin node in the body." + } + /** Warnings about shadowing names. */ sealed trait Shadowed extends Warning { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala index 1f44a273d93d..3758bcea82b6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala @@ -8,7 +8,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.AliasAnalysis import org.enso.compiler.pass.desugar._ import org.enso.compiler.pass.optimise.LambdaConsolidate -import org.enso.compiler.pass.resolve.IgnoredBindings +import org.enso.compiler.pass.resolve.{ExpressionAnnotations, IgnoredBindings} import scala.annotation.unused @@ -110,7 +110,6 @@ case object UnusedBindings extends IRPass { .unsafeAs[AliasAnalysis.Info.Occurrence] val isUsed = aliasInfo.graph.linksFor(aliasInfo.id).nonEmpty - // FIXME: take into account @Builtin_Method if (!isIgnored && !isUsed) { binding .copy(expression = runExpression(binding.expression, context)) @@ -136,9 +135,23 @@ case object UnusedBindings extends IRPass { case IR.Function.Lambda(_, _: IR.Foreign.Definition, _, _, _, _) => function case lam @ IR.Function.Lambda(args, body, _, _, _, _) => + val isBuiltin = isBuiltinMethod(body) + val lintedArgs = + if (isBuiltin) args + else args.map(lintFunctionArgument(_, context)) + val body1 = runExpression(body, context) + val lintedBody = if (isBuiltin) + body match { + case _: IR.Literal.Text => + body1 + case _ => + body1.addDiagnostic(IR.Warning.WrongBuiltinMethod(body.location)) + } + else body1 + lam.copy( - arguments = args.map(lintFunctionArgument(_, context)), - body = runExpression(body, context) + arguments = lintedArgs, + body = lintedBody ) case _: IR.Function.Binding => throw new CompilerError( @@ -260,4 +273,17 @@ case object UnusedBindings extends IRPass { ) } } + + /** Checks if the expression has a @Builtin_Method annotation + * + * @param expression the expression to check + * @return 'true' if 'expression' has @Builtin_Method annotation, otherwise 'false' + */ + private def isBuiltinMethod(expression: IR.Expression): Boolean = { + expression + .getMetadata(ExpressionAnnotations) + .exists(_.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName)) + } + + } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index 549780ff144f..008a8faa5016 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -11,7 +11,7 @@ class PolyglotTest extends InterpreterTest { "allow calling methods on static objects" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | class = Java.lookup_class "org.enso.example.TestClass" @@ -24,7 +24,7 @@ class PolyglotTest extends InterpreterTest { "allow instantiating objects and calling methods on them" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | class = Java.lookup_class "org.enso.example.TestClass" @@ -36,7 +36,7 @@ class PolyglotTest extends InterpreterTest { "allow listing available members of an object" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | class = Java.lookup_class "org.enso.example.TestClass" diff --git a/test/Tests/src/Semantic/Case_Spec.enso b/test/Tests/src/Semantic/Case_Spec.enso index d70c01ca5bf6..8402260df495 100644 --- a/test/Tests/src/Semantic/Case_Spec.enso +++ b/test/Tests/src/Semantic/Case_Spec.enso @@ -1,5 +1,5 @@ from Standard.Base import all - +import Standard.Builtins import Standard.Test polyglot java import java.util.Random @@ -68,10 +68,10 @@ spec = Test.group "Pattern Matches" <| Test.specify "should be able to match on the Polyglot type" <| random_gen = Random.new case random_gen of - Polyglot -> Nothing + Builtins.Polyglot -> Nothing _ -> Test.fail "Expected a polyglot object to match." - case Polyglot of - Polyglot -> Nothing + case Builtins.Polyglot of + Builtins.Polyglot -> Nothing _ -> Test.fail "Expected the Polyglot constructor to match." Test.specify "should be able to match on the Any type" <| value_1 = 1.23143 @@ -82,7 +82,7 @@ spec = Test.group "Pattern Matches" <| case value_2 of Any -> Nothing _ -> Test.fail "Expected any value to match Any." - case Polyglot of + case Builtins.Polyglot of Any -> Nothing _ -> Test.fail "Expect any constructor to match Any." case Any of diff --git a/test/Tests/src/Semantic/Meta_Spec.enso b/test/Tests/src/Semantic/Meta_Spec.enso index 24644db5d1a0..1ca122932d14 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -1,6 +1,7 @@ from Standard.Base import all import Standard.Base.System.Platform from Standard.Base.Data.Text.Text_Sub_Range import Last +import Standard.Builtins import Standard.Test @@ -62,7 +63,7 @@ spec = Test.group "Meta-Value Manipulation" <| 1.0.is_a Text . should_be_false random_gen = Random.new - Meta.is_a random_gen Polyglot . should_be_true + Meta.is_a random_gen Builtins.Polyglot . should_be_true Meta.is_an random_gen Integer . should_be_false (My_Type 1 "foo" Nothing).is_a My_Type . should_be_true @@ -81,7 +82,7 @@ spec = Test.group "Meta-Value Manipulation" <| _ -> Nothing Test.specify "should allow to get the source location of a frame" pending=location_pending <| src = Meta.get_source_location 0 - loc = "Meta_Spec.enso:83:15-40" + loc = "Meta_Spec.enso:84:15-40" src.take (Last loc.length) . should_equal loc Test.specify "should allow to get qualified type names of values" <| From 6afa443919511e54b312847a40ec6548edc3efc3 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 4 Apr 2022 10:22:48 +0200 Subject: [PATCH 03/73] Move Array type out of Builtins The change moves another type, Array, out of Builtins.enso. Also introduced a couple of changes to make it possible: - Complex Types cannot erase annotations of its atoms - method lookup algorithm has to take into account situation where Complex Type, it's Atom *and* module use the same name, which makes name resolution slightly ambiguous. The new version ensures that we don't have to use qualified names *every single time* This change introduces some lookup maps for checking if the given atom constructor is a builtin type. Using maps (and strings as keys) is not always necessary or unambiguous, and will work on a more permanent solution. --- .../Base/0.0.0-dev/src/Data/Array.enso | 179 +++++++++++++++ .../0.0.0-dev/src/Data/Array/Extensions.enso | 18 -- .../src/Data/Text/Regex/Engine/Default.enso | 4 +- .../Base/0.0.0-dev/src/Data/Vector.enso | 5 +- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 11 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 10 + .../Base/0.0.0-dev/src/Polyglot/Java.enso | 40 +++- .../0.0.0-dev/src/Runtime/Extensions.enso | 6 +- .../Base/0.0.0-dev/src/System/File.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Warning.enso | 6 +- .../caseexpr/BranchNodeFactory.java | 16 ++ .../number/smallInteger/ToDecimalNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 79 ++++--- .../interpreter/runtime/builtin/Mutable.java | 21 +- .../runtime/scope/ModuleScope.java | 41 ++++ .../interpreter/runtime/type/Constants.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 209 ------------------ .../scala/org/enso/compiler/Compiler.scala | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 27 ++- .../codegen/RuntimeStubsGenerator.scala | 10 +- .../org/enso/compiler/data/BindingsMap.scala | 3 +- .../pass/analyse/BindingAnalysis.scala | 14 +- .../compiler/pass/desugar/ComplexType.scala | 9 +- .../test/semantic/SystemProcessTest.scala | 24 ++ test/Tests/src/Data/Array_Spec.enso | 2 + test/Tests/src/Semantic/Case_Spec.enso | 11 +- test/Tests/src/Semantic/Meta_Spec.enso | 7 +- 28 files changed, 432 insertions(+), 330 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array/Extensions.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso new file mode 100644 index 000000000000..666f2b84055c --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso @@ -0,0 +1,179 @@ +import Standard.Base.Data.Vector + +## Utilities for working with primitive arrays. +type Array + + ## The type of primitive mutable arrays. + @Builtin_Type + type Array + + ## Gets the element at index in the array this. + + Arguments: + - index: The index to get the element from. + + ? Safety + If index < 0 or index >= this.length, then this operation will result + in an Invalid_Array_Index_Error exception. + + > Example + Get the element at index 1. + + [1,2,3].to_array.at 1 + at : Integer -> Any + at index = @Builtin_Method "Array.at" + + ## Set the cell at the specified index to the provided value, returning + the array. + + Arguments: + - index: The position in the array to set. + - value: The value to set at position index. + + The array is mutated in place, and only returned to facilitate a natural + programming style in Enso. + + ? Safety + If index < 0 or index >= this.length, then this operation will result + in an Invalid_Array_Index_Error exception. + set_at : Integer -> Any -> Array + set_at index value = @Builtin_Method "Array.set_at" + + ## Gets the length of the array this. + + > Example + Getting the length of an array. + + [1,2,3].to_array.length + length : Integer + length = @Builtin_Method "Array.length" + + ## Sorts the this array in place. + + Arguments: + - comparator: A comparison function that takes two elements and returns + an Ordering that describes how the first element is ordered with + respect to the second. + + > Example + Sorting an array of numbers. + + [1,2,3].to_array.sort + sort : (Any -> Any -> Ordering) -> Nothing + sort comparator = @Builtin_Method "Array.sort" + + ## Identity. + + This method is implemented purely for completeness with the runtime's + primitive array protocol. + to_array : Array + to_array = @Builtin_Method "Array.to_array" + + ## UNSTABLE + ADVANCED + + Returns a Text used to display this value in the IDE. + + The particular representation is left unspecified and subject to change in + the future. The current implementation uses JSON serialization as the + default. + + > Example + Converting an array to its default visualization representation. + + [1, 2, 3, 4].to_array.to_default_visualization_data + to_default_visualization_data : Text + to_default_visualization_data = + Vector.Vector this . to_default_visualization_data + +## Creates an array with length 0. + + > Example + Create an empty array. + + Array.empty +empty : Array +empty = @Builtin_Method "Array.empty" + +## Creates a new array of length size, with all elements uninitialized. + + Arguments: + - size: The size of the array to create. + + > Example + Create a new array of size 10. + + Array.new 10 +new : Integer -> Array +new size = @Builtin_Method "Array.new" + +## PRIVATE + + Create an array with one element provided. + + Arguments: + - item_1: The one element in the array. +new_1 : Any -> Array +new_1 item_1 = @Builtin_Method "Array.new_1" + +## PRIVATE + + Create an array with two elements provided. + + Arguments: + - item_1: The first element. + - item_2: The second element. +new_2 : Any -> Any -> Array +new_2 item_1 item_2 = @Builtin_Method "Array.new_2" + +## PRIVATE + + Create an array with three elements provided. + + Arguments: + - item_1: The first element. + - item_2: The second element. + - item_3: The third element. +new_3 : Any -> Any -> Any -> Array +new_3 item_1 item_2 item_3 = @Builtin_Method "Array.new_3" + +## PRIVATE + + Create an array with four elements provided. + + Arguments: + - item_1: The first element. + - item_2: The second element. + - item_3: The third element. + - item_4: The fourth element. +new_4 : Any -> Any -> Any -> Any -> Array +new_4 item_1 item_2 item_3 item_4 = @Builtin_Method "Array.new_4" + +## Copies from the source array, beginning at the specified position, to the + specified position in the destination array. + + Arguments: + - src: The source array. + - source_index: The start position in the src array. + - dest: The desination array. + - dest_index: The start position in the that array. + + A subsequence of array elements are copied from the src array to the + dest array. The number of components copied is equal to count. The + components at positions source_index through source_index + count - 1 + in the strc array are copied into positions dest_index through + dest_index + count - 1, respectively, of the destination array. + + If the src and dest arguments refer to the same array, then the copy + is performed as if the components at positions source_index through + source_index + count - 1 are first copied to a temporary array with + length count, and then the contents of the temporary array are copied + into positions dest_index through dest_index + count - 1 of the + destination array. + + > Example + Copying elements from one array to another. + + Array.copy [1,2,3].to_array 0 (Vector.fill 3 0).to_array 0 3 +copy : Array -> Integer -> Array -> Integer -> Integer -> Nothing +copy src source_index dest dest_index count = @Builtin_Method "Array.copy" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array/Extensions.enso deleted file mode 100644 index caa2b106f2f8..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array/Extensions.enso +++ /dev/null @@ -1,18 +0,0 @@ -from Standard.Base import all - -## UNSTABLE - ADVANCED - - Returns a Text used to display this value in the IDE. - - The particular representation is left unspecified and subject to change in - the future. The current implementation uses JSON serialization as the - default. - - > Example - Converting an array to its default visualization representation. - - [1, 2, 3, 4].to_array.to_default_visualization_data -Array.to_default_visualization_data : Text -Array.to_default_visualization_data = - Vector.Vector this . to_default_visualization_data diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso index 96e09c364c34..5a9cd3f7d5b7 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso @@ -39,11 +39,9 @@ import Standard.Base.Data.Text.Regex import Standard.Base.Data.Text.Regex.Engine import Standard.Base.Data.Text.Regex.Option as Global_Option import Standard.Base.Data.Text.Regex.Mode -import Standard.Base.Polyglot.Java as Java_Ext +import Standard.Base.Polyglot.Java from Standard.Base.Data.Text.Span as Span_Module import Utf_16_Span -from Standard.Builtins import Java - import Standard.Base.Error.Extensions as Errors polyglot java import java.lang.IllegalArgumentException diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso index 2d18b0902713..0e1469e8a489 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso @@ -1,5 +1,4 @@ from Standard.Base import all -from Standard.Builtins import Array from Standard.Builtins import Unsupported_Argument_Types ## Creates a new vector of the given length, initializing elements using @@ -89,7 +88,7 @@ new_builder = Builder.new If this didn't happen then it would be possible for the underlying array to be mutated under the hood, and sneak mutability into our immutable data. from_array : Any -> Vector.Vector Any -from_array arr = here.new (Base.Polyglot.get_array_size arr) (arr.at _) +from_array arr = here.new (Polyglot.get_array_size arr) (arr.at _) ## The basic, immutable, vector type. type Vector @@ -121,7 +120,7 @@ type Vector [1, 2, 3, 4].length length : Number - length = Base.Polyglot.get_array_size this.to_array + length = Polyglot.get_array_size this.to_array ## Gets an element from the vector at a specified index (0-based). diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index ba258d2b2a32..c269fc34714c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -1,5 +1,5 @@ import project.Data.Any.Extensions -import project.Data.Array.Extensions +import project.Data.Array import project.Data.Interval import project.Data.Json import project.Data.List @@ -40,14 +40,14 @@ export project.Data.Ordering.Sort_Order export project.Data.Vector export project.Math export project.Meta -export project.Polyglot +export project.Polyglot.Java export project.System.Environment export project.System.File export project.Data.Text.Regex.Mode as Regex_Mode export project.Warning +from project.Data.Array export Array from project.Data.Any.Extensions export all -from project.Data.Array.Extensions export all from project.Data.List export Nil, Cons from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise @@ -65,8 +65,7 @@ from project.Data.Text.Matching export Case_Insensitive, Text_Matcher, Regex_Mat from project.Error.Common export all from project.Error.Extensions export all from project.Meta.Enso_Project export all -from project.Polyglot.Java export all +from project.Polyglot export all from project.Runtime.Extensions export all -from Standard.Builtins export all hiding Meta, Less, Equal, Greater, Ordering, Polyglot - +from Standard.Builtins export all hiding Meta, Less, Equal, Greater, Ordering diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso index 5892676afcb4..52919c6bfcc9 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso @@ -86,7 +86,7 @@ is_a value typ = if typ == Any then True else Number -> if typ == Number then True else case value of Integer -> typ == Integer Decimal -> typ == Decimal - Builtins.Polyglot -> typ == Builtins.Polyglot + Base.Polyglot -> typ == Base.Polyglot _ -> meta_val = here.meta value case meta_val of diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso index cc26d4ee40d4..43c03bc0404b 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -1,3 +1,13 @@ +## Generic utilities for interacting with other languages. +type Polyglot + + ## A type representing interactions with polyglot languages. + Polyglot is a term that refers to other languages (such as Java) that are + running on the same JVM. + + @Builtin_Type + type Polyglot + ## Reads the number of elements in a given polyglot array object. Arguments: diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Java.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Java.enso index e3f371fce563..61b3d1edc94f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Java.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Java.enso @@ -1,6 +1,38 @@ -from Standard.Base import all +## Utilities for working with Java polyglot objects. +type Java -import Standard.Builtins + ## A type for operations specific to Java polyglot objects. + type Java + + ## Adds the provided entry to the host class path. + + Arguments: + - path: The java classpath entry to add. + + Use of the actual polyglot imports system should be preferred to use of + this method. + + > Example + Adding Random to the classpath. + + Java.add_to_class_path "java.util.Random" + add_to_class_path : Text -> Nothing + add_to_class_path path = @Builtin_Method "Java.add_to_class_path" + +## Looks up a java symbol on the classpath by name. + + Arguments: + - name: The name of the java symbol to look up. + + Use of the actual polyglot imports system should be preferred to use of + this method. + + > Example + Look up java's Random class. + + Java.lookup_class "java.util.Random" +lookup_class : Text -> Any +lookup_class name = @Builtin_Method "Java.lookup_class" ## PRIVATE @@ -9,7 +41,7 @@ import Standard.Builtins Arguments: - object: The object to check for class membership. - class: The java class to check for membership in. -Builtins.Java.is_instance : Any -> Any -> Boolean -Builtins.Java.is_instance object class = +is_instance : Any -> Any -> Boolean +is_instance object class = class_object = class.class class_object.isInstance object diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso index c2f2f395bc13..083fab6d8f6f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso @@ -90,8 +90,8 @@ Runtime.get_stack_trace = ## PRIVATE Converts a primitive stack trace element into the regular one. wrap_primitive_stack_trace_element el = - loc = case Base.Polyglot.has_source_location el of - True -> Source_Location (Base.Polyglot.get_source_location el) + loc = case Polyglot.has_source_location el of + True -> Source_Location (Polyglot.get_source_location el) False -> Nothing - name = Base.Polyglot.get_executable_name el + name = Polyglot.get_executable_name el Stack_Trace_Element name loc diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso index 2d7055385fb2..d2ec6ac6f410 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso @@ -867,7 +867,7 @@ type File_Error list_immediate_children : File -> Vector.Vector File list_immediate_children directory = arr = directory.prim_file.list - Vector.new (Base.Polyglot.get_array_size arr) ix-> + Vector.new (Polyglot.get_array_size arr) ix-> File (arr.at ix) ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso index 44d7af345437..6c51a4f2bfd4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso @@ -39,10 +39,10 @@ type Warning reassignments : Vector.Vector Stack_Trace_Element reassignments = Vector.Vector (Prim_Warning.get_reassignments this.prim_warning) . map r-> - loc = case Base.Polyglot.has_source_location r of + loc = case Polyglot.has_source_location r of False -> Nothing - True -> Source_Location (Base.Polyglot.get_source_location r) - Stack_Trace_Element (Base.Polyglot.get_executable_name r) loc + True -> Source_Location (Polyglot.get_source_location r) + Stack_Trace_Element (Polyglot.get_executable_name r) loc ## UNSTABLE diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java new file mode 100644 index 000000000000..a9e471708c21 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java @@ -0,0 +1,16 @@ +package org.enso.interpreter.node.controlflow.caseexpr; + +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import com.oracle.truffle.api.RootCallTarget; + +/** + * BranchNodeFactory is a SAM-type to allow for storing the mapping between + * AtomConstructors and corresponding BranchNode. + * + * SAM-type is necessary because types like + * `PolyglotBranchNode.build _` + + */ +public interface BranchNodeFactory { + BranchNode create(AtomConstructor atomConstructor, RootCallTarget target); +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ToDecimalNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ToDecimalNode.java index a87ac7efb2a5..971aac643c46 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ToDecimalNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ToDecimalNode.java @@ -4,7 +4,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; @BuiltinMethod( - type = "Small_Int", + type = "Small_Integer", name = "to_decimal", description = "Conversion of integers to decimals.") public class ToDecimalNode extends Node { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index da9490243c42..bcfea9020eb9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -70,6 +70,9 @@ public static class Debug { } private HashMap>> builtinNodes; + // TODO Consider dropping the map and just assigning to a single variable since builtin types + // should be unique + private HashMap builtinTypes; private final AtomConstructor any; private final AtomConstructor debug; @@ -88,7 +91,6 @@ public static class Debug { private final Mutable mutable; private final Number number; private final Ordering ordering; - private final AtomConstructor polyglot; private final Resource resource; private final System system; private final Text text; @@ -104,6 +106,7 @@ public Builtins(Context context) { module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); scope = module.compileScope(context); builtinNodes = new HashMap<>(); + builtinTypes = new HashMap<>(); any = new AtomConstructor("Any", scope).initializeFields(); bool = new Bool(language, scope); @@ -119,7 +122,7 @@ public Builtins(Context context) { error = new Error(language, scope); function = new AtomConstructor("Function", scope).initializeFields(); meta = new Meta(language, scope); - mutable = new Mutable(language, scope); + mutable = new Mutable(this, language, scope); nothing = new AtomConstructor("Nothing", scope).initializeFields(); number = new Number(language, scope); ordering = new Ordering(language, scope); @@ -130,9 +133,6 @@ public Builtins(Context context) { new ArgumentDefinition(0, "payload", ArgumentDefinition.ExecutionMode.EXECUTE), new ArgumentDefinition( 1, "internal_original_exception", ArgumentDefinition.ExecutionMode.EXECUTE)); - // TODO remove once @Builtin_Type is handled - polyglot = new AtomConstructor("Polyglot", scope).initializeFields(); - scope.registerConstructor(polyglot); resource = new Resource(language, scope); system = new System(language, scope); text = new Text(language, scope); @@ -149,7 +149,6 @@ public Builtins(Context context) { AtomConstructor runtime = new AtomConstructor("Runtime", scope).initializeFields(); AtomConstructor state = new AtomConstructor("State", scope).initializeFields(); - AtomConstructor java = new AtomConstructor("Java", scope).initializeFields(); AtomConstructor thread = new AtomConstructor("Thread", scope).initializeFields(); AtomConstructor unsafe = new AtomConstructor("Unsafe", scope).initializeFields(); @@ -167,8 +166,6 @@ public Builtins(Context context) { scope.registerConstructor(debug); scope.registerConstructor(projectDescription); scope.registerConstructor(runtime); - - scope.registerConstructor(java); scope.registerConstructor(thread); scope.registerConstructor(unsafe); @@ -208,14 +205,11 @@ public Builtins(Context context) { scope.registerMethod(any, "to_text", AnyToTextMethodGen.makeFunction(language)); scope.registerMethod(any, "to_display_text", AnyToDisplayTextMethodGen.makeFunction(language)); - scope.registerMethod(java, "add_to_class_path", AddToClassPathMethodGen.makeFunction(language)); - scope.registerMethod(java, "lookup_class", LookupClassMethodGen.makeFunction(language)); - scope.registerMethod( thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); - readAllBuiltinNodes(); + readAllBuiltinNodes(scope); } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ @@ -257,35 +251,43 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } @CompilerDirectives.TruffleBoundary - public void readAllBuiltinNodes() { - try { - Reflections reflections = new Reflections("org.enso.interpreter.node.expression.builtin"); - Set subtypes = reflections.get(Scanners.SubTypes.of(Scanners.TypesAnnotated.with(NodeInfo.class))); - subtypes.stream().forEach(className -> { - try { - Class clazz = (Class) Class.forName(className); - NodeInfo info = clazz.getDeclaredAnnotation(NodeInfo.class); - String[] name = info.shortName().split("\\."); - if (name.length == 2 && !name[0].isEmpty()) { + public void readAllBuiltinNodes(ModuleScope scope) { + Reflections reflections = new Reflections("org.enso.interpreter.node.expression.builtin"); + Set subtypes = reflections.get(Scanners.SubTypes.of(Scanners.TypesAnnotated.with(NodeInfo.class))); + subtypes.stream().forEach(className -> { + try { + Class clazz = (Class) Class.forName(className); + NodeInfo info = clazz.getDeclaredAnnotation(NodeInfo.class); + String[] name = info.shortName().split("\\."); + if (name.length == 2 && !name[0].isEmpty()) { + scope.getLocalConstructor(name[0]).ifPresentOrElse(constr -> { Map> atomNodes = builtinNodes.get(name[0]); if (atomNodes == null) { atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + builtinNodes.put(constr.getName(), atomNodes); + } + atomNodes.put(name[1], clazz); + }, () -> { + Map> atomNodes = builtinNodes.get(name[0]); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone builtinNodes.put(name[0], atomNodes); } atomNodes.put(name[1], clazz); - } - } catch (Exception e) { - e.printStackTrace(); + }); } - // todo: handle gracefully other cases - }); - } catch (Exception e) { - e.printStackTrace(); - } + } catch (Exception e) { + throw new CompilerError(e.getMessage()); + } + // todo: handle gracefully other cases + }); } - public Optional getBuiltinFunction(String atomName, String methodName, Language language) { - Map> atomNodes = builtinNodes.get(atomName); + public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { + // TODO: move away from String mapping once Builtins is gone + Map> atomNodes = builtinNodes.get(atom.getName()); if (atomNodes == null) return Optional.empty(); Class clazz = atomNodes.get(methodName); @@ -300,6 +302,17 @@ public Optional getBuiltinFunction(String atomName, String methodName, } } + public void registerBuiltinType(AtomConstructor atom) { + if (builtinTypes.containsKey(atom.getName())) { + throw new CompilerError("Builtin type '" + atom.getName() + "' already registered"); + } + builtinTypes.put(atom.getName(), atom); + } + + public AtomConstructor getBuiltinType(String name) { + return builtinTypes.get(name); + } + /** * Returns the {@code Nothing} atom constructor. * @@ -381,7 +394,7 @@ public Mutable mutable() { /** @return the container for polyglot-related builtins. */ public AtomConstructor polyglot() { - return polyglot; + return builtinTypes.get("Polyglot"); } /** @return the {@code Caught_Panic} atom constructor */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java index 3e055e01e228..fd41fe9a1036 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java @@ -9,6 +9,7 @@ public class Mutable { private final AtomConstructor array; private final AtomConstructor ref; + private final Builtins builtins; /** * Creates a new instance of this class, registering all relevant bindings in the provided scope. @@ -16,21 +17,9 @@ public class Mutable { * @param language the current language instance. * @param scope the scope for builtin methods. */ - public Mutable(Language language, ModuleScope scope) { - array = new AtomConstructor("Array", scope).initializeFields(); - scope.registerConstructor(array); - scope.registerMethod(array, "empty", EmptyMethodGen.makeFunction(language)); - scope.registerMethod(array, "new", NewMethodGen.makeFunction(language)); - scope.registerMethod(array, "new_1", New1MethodGen.makeFunction(language)); - scope.registerMethod(array, "new_2", New2MethodGen.makeFunction(language)); - scope.registerMethod(array, "new_3", New3MethodGen.makeFunction(language)); - scope.registerMethod(array, "new_4", New4MethodGen.makeFunction(language)); - scope.registerMethod(array, "length", LengthMethodGen.makeFunction(language)); - scope.registerMethod(array, "to_array", ToArrayMethodGen.makeFunction(language)); - scope.registerMethod(array, "at", GetAtMethodGen.makeFunction(language)); - scope.registerMethod(array, "set_at", SetAtMethodGen.makeFunction(language)); - scope.registerMethod(array, "copy", CopyMethodGen.makeFunction(language)); - scope.registerMethod(array, "sort", SortMethodGen.makeFunction(language)); + public Mutable(Builtins builtins, Language language, ModuleScope scope) { + array = null; + this.builtins = builtins; ref = new AtomConstructor("Ref", scope).initializeFields(); scope.registerConstructor(ref); @@ -41,7 +30,7 @@ public Mutable(Language language, ModuleScope scope) { /** @return the Array constructor. */ public AtomConstructor array() { - return array; + return builtins.getBuiltinType("Array"); } /** @return the Ref constructor. */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index b349960d91d5..33ae1c98b608 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -19,6 +19,7 @@ public class ModuleScope implements TruffleObject { private final Module module; private Map polyglotSymbols = new HashMap<>(); private Map constructors = new HashMap<>(); + private List builtins = new ArrayList<>(); private Map> methods = new HashMap<>(); private Map> conversions = new HashMap<>(); private Set imports = new HashSet<>(); @@ -43,6 +44,15 @@ public void registerConstructor(AtomConstructor constructor) { constructors.put(constructor.getName(), constructor); } + public void registerBuiltinConstructor(AtomConstructor constructor) { + registerConstructor(constructor); + builtins.add(constructor); + } + + public boolean isBuiltin(AtomConstructor constructor) { + return builtins.contains(constructor); + } + /** @return the associated type of this module. */ public AtomConstructor getAssociatedType() { return associatedType; @@ -196,6 +206,37 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { if (definedWithAtom != null) { return definedWithAtom; } + + // Additional check for Builtin_Type's + // Consider a module Foo.enso in std library:: + // type Foo + // @Builtin_Type + // type Foo + // length = 0 + // new size = @Builtin_Method ... + // + // a) you want to be able to match on it like + // ``` + // case x of + // Foo -> ... + // ``` + // and not + // ``` + // case x of + // Foo.Foo -> ... + // ``` + // and yet you still want to be able to call + // `Foo.new` + // Enhancing the method definition lookup for Builtin_Types allows you to avoid + // introducing additional import statements, especially for atom Builtin_Type. + AtomConstructor moduleType = atom.getDefinitionScope().associatedType; + if (atom != moduleType && atom.getDefinitionScope().isBuiltin(atom)) { + definedWithAtom = atom.getDefinitionScope().getMethodMapFor(moduleType).get(lowerName); + if (definedWithAtom != null) { + return definedWithAtom; + } + } + Function definedHere = getMethodMapFor(atom).get(lowerName); if (definedHere != null) { return definedHere; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 731d9ad32f57..4c3e8f0e5cc2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -4,7 +4,7 @@ public class Constants { public static final String ANY = "Standard.Builtins.Main.Any"; - public static final String ARRAY = "Standard.Builtins.Main.Array"; + public static final String ARRAY = "Standard.Data.Main.Array"; public static final String BOOLEAN = "Standard.Builtins.Main.Boolean"; public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; public static final String ERROR = "Standard.Builtins.Main.Error"; diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 3541ee470adc..003c39ffe336 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -486,53 +486,6 @@ type Function call : Any call = @Builtin_Method "Function.call" -## Generic utilities for interacting with other languages. -type Polyglot - - ## A type representing interactions with polyglot languages. - - Polyglot is a term that refers to other languages (such as Java) that are - running on the same JVM. - - @Builtin_Type - type Polyglot - -## Utilities for working with Java polyglot objects. -type Java - - ## A type for operations specific to Java polyglot objects. - type Java - - ## Adds the provided entry to the host class path. - - Arguments: - - path: The java classpath entry to add. - - Use of the actual polyglot imports system should be preferred to use of - this method. - - > Example - Adding Random to the classpath. - - Java.add_to_class_path "java.util.Random" - add_to_class_path : Text -> Nothing - add_to_class_path path = @Builtin_Method "Java.add_to_class_path" - - ## Looks up a java symbol on the classpath by name. - - Arguments: - - name: The name of the java symbol to look up. - - Use of the actual polyglot imports system should be preferred to use of - this method. - - > Example - Look up java's Random class. - - Java.lookup_class "java.util.Random" - lookup_class : Text -> Any - lookup_class name = @Builtin_Method "Java.lookup_class" - ## Primitive IO operations internal to the runtime. type Prim_Io @@ -788,168 +741,6 @@ type Meta get_qualified_type_name : Any -> Text get_qualified_type_name value = @Builtin_Method "Meta.get_qualified_type_name" -## Utilities for working with primitive arrays. -type Array - - ## The type of primitive mutable arrays. - @Builtin_Type - type Array - - ## Creates an array with length 0. - - > Example - Create an empty array. - - Array.empty - empty : Array - empty = @Builtin_Method "Array.empty" - - ## Creates a new array of length size, with all elements uninitialized. - - Arguments: - - size: The size of the array to create. - - > Example - Create a new array of size 10. - - Array.new 10 - new : Integer -> Array - new size = @Builtin_Method "Array.new" - - ## PRIVATE - - Create an array with one element provided. - - Arguments: - - item_1: The one element in the array. - new_1 : Any -> Array - new_1 item_1 = @Builtin_Method "Array.new_1" - - ## PRIVATE - - Create an array with two elements provided. - - Arguments: - - item_1: The first element. - - item_2: The second element. - new_2 : Any -> Any -> Array - new_2 item_1 item_2 = @Builtin_Method "Array.new_2" - - ## PRIVATE - - Create an array with three elements provided. - - Arguments: - - item_1: The first element. - - item_2: The second element. - - item_3: The third element. - new_3 : Any -> Any -> Any -> Array - new_3 item_1 item_2 item_3 = @Builtin_Method "Array.new_3" - - ## PRIVATE - - Create an array with four elements provided. - - Arguments: - - item_1: The first element. - - item_2: The second element. - - item_3: The third element. - - item_4: The fourth element. - new_4 : Any -> Any -> Any -> Any -> Array - new_4 item_1 item_2 item_3 item_4 = @Builtin_Method "Array.new_4" - - ## Copies from the source array, beginning at the specified position, to the - specified position in the destination array. - - Arguments: - - src: The source array. - - source_index: The start position in the src array. - - dest: The desination array. - - dest_index: The start position in the that array. - - A subsequence of array elements are copied from the src array to the - dest array. The number of components copied is equal to count. The - components at positions source_index through source_index + count - 1 - in the strc array are copied into positions dest_index through - dest_index + count - 1, respectively, of the destination array. - - If the src and dest arguments refer to the same array, then the copy - is performed as if the components at positions source_index through - source_index + count - 1 are first copied to a temporary array with - length count, and then the contents of the temporary array are copied - into positions dest_index through dest_index + count - 1 of the - destination array. - - > Example - Copying elements from one array to another. - - Array.copy [1,2,3].to_array 0 (Vector.fill 3 0).to_array 0 3 - copy : Array -> Integer -> Array -> Integer -> Integer -> Nothing - copy src source_index dest dest_index count = - @Builtin_Method "Array.copy" - - ## Gets the element at index in the array this. - - Arguments: - - index: The index to get the element from. - - ? Safety - If index < 0 or index >= this.length, then this operation will result - in an Invalid_Array_Index_Error exception. - - > Example - Get the element at index 1. - - [1,2,3].to_array.at 1 - at : Integer -> Any - at index = @Builtin_Method "Array.at" - - ## Set the cell at the specified index to the provided value, returning - the array. - - Arguments: - - index: The position in the array to set. - - value: The value to set at position index. - - The array is mutated in place, and only returned to facilitate a natural - programming style in Enso. - - ? Safety - If index < 0 or index >= this.length, then this operation will result - in an Invalid_Array_Index_Error exception. - set_at : Integer -> Any -> Array - set_at index value = @Builtin_Method "Array.set_at" - - ## Gets the length of the array this. - - > Example - Getting the length of an array. - - [1,2,3].to_array.length - length : Integer - length = @Builtin_Method "Array.length" - - ## Sorts the this array in place. - - Arguments: - - comparator: A comparison function that takes two elements and returns - an Ordering that describes how the first element is ordered with - respect to the second. - - > Example - Sorting an array of numbers. - - [1,2,3].to_array.sort - sort : (Any -> Any -> Ordering) -> Nothing - sort comparator = @Builtin_Method "Array.sort" - - ## Identity. - - This method is implemented purely for completeness with the runtime's - primitive array protocol. - to_array : Array - to_array = @Builtin_Method "Array.to_array" - ## Utilities for working with mutable references. type Ref diff --git a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala index 5a6c49bbaf0e..9514256684bc 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -46,7 +46,7 @@ class Compiler( private val passManager: PassManager = passes.passManager private val importResolver: ImportResolver = new ImportResolver(this) private val stubsGenerator: RuntimeStubsGenerator = - new RuntimeStubsGenerator() + new RuntimeStubsGenerator(builtins) private val irCachingEnabled = !context.isIrCachingDisabled private val useGlobalCacheLocations = context.getEnvironment.getOptions.get( RuntimeOptions.USE_GLOBAL_IR_CACHE_LOCATION_KEY diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 2ad2a6d0553a..d4fff69d4954 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -36,8 +36,9 @@ import org.enso.interpreter.{Constants, Language} import java.math.BigInteger import org.enso.compiler.core.IR.Name.Special +import org.enso.pkg.QualifiedName -import scala.collection.mutable +import scala.collection.{immutable, mutable} import scala.collection.mutable.ArrayBuffer /** This is an implementation of a codegeneration pass that lowers the Enso @@ -244,7 +245,7 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => - val builtinFunction = context.getBuiltins.getBuiltinFunction(cons.getName(), methodDef.methodName.name, language) + val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) builtinFunction.orElseThrow(() => new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) case fn: IR.Function => val (body, arguments) = @@ -792,10 +793,10 @@ class IrToTruffle( runtimeConsOpt.map { atomCons => val any = context.getBuiltins.any - val array = context.getBuiltins.mutable.array + //val array = context.getBuiltins.mutable().array() val bool = context.getBuiltins.bool val number = context.getBuiltins.number - val polyglot = context.getBuiltins.polyglot + //val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text val branchNode: BranchNode = if (atomCons == bool.getTrue) { @@ -818,10 +819,9 @@ class IrToTruffle( ) } else if (atomCons == number.getNumber) { NumberBranchNode.build(number, branchCodeNode.getCallTarget) - } else if (atomCons == array) { - ArrayBranchNode.build(array, branchCodeNode.getCallTarget) - } else if (atomCons == polyglot) { - PolyglotBranchNode.build(polyglot, branchCodeNode.getCallTarget) + } else if (atomCons.getDefinitionScope.isBuiltin(atomCons)) { + val key = (atomCons.getDefinitionScope.getModule.getName, atomCons.getName) + branchNodeFactories(key).create(atomCons, branchCodeNode.getCallTarget) } else if (atomCons == any) { CatchAllBranchNode.build(branchCodeNode.getCallTarget) } else { @@ -848,6 +848,17 @@ class IrToTruffle( } } + // FIXME: Consider a different key mapping, and going back to reference + // checking from builtins, if too expensive and automatic mapping + // is not necessary. + // SAM-type BranchNodeFactory is necessary here because types like + // (array: AtomConstructor, branch: RootCallTarget) -> BranchNode + // and related eta-expansion appear to crash Graal (not a joke). + private val branchNodeFactories: Map[(QualifiedName, String), BranchNodeFactory] = immutable.HashMap[(QualifiedName, String), BranchNodeFactory]( + (QualifiedName(List("Standard", "Base"), "Polyglot"), "Polyglot") -> PolyglotBranchNode.build _, + (QualifiedName(List("Standard", "Base", "Data"), "Array"), "Array") -> ArrayBranchNode.build _, + ) + /* Note [Pattern Match Fallbacks] * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Enso in its current state has no coverage checking for constructors on diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index aba013947586..fd916afdf63f 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -2,13 +2,14 @@ package org.enso.compiler.codegen import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.interpreter.runtime.Module +import org.enso.interpreter.runtime.builtin.Builtins import org.enso.interpreter.runtime.callable.atom.AtomConstructor /** Generates stubs of runtime representations of atom constructors, to allow * [[IrToTruffle the code generator]] to refer to constructors that are not * fully generated yet. */ -class RuntimeStubsGenerator() { +class RuntimeStubsGenerator(builtins: Builtins) { /** Runs the stage on the given module. * @@ -23,7 +24,12 @@ class RuntimeStubsGenerator() { ) localBindings.types.foreach { tp => val constructor = new AtomConstructor(tp.name, scope) - scope.registerConstructor(constructor) + if (tp.builtinType) { + scope.registerBuiltinConstructor(constructor) + builtins.registerBuiltinType(constructor) + } else { + scope.registerConstructor(constructor) + } } } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index 10dfb712b30a..34511920938a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala @@ -717,8 +717,9 @@ object BindingsMap { * * @param name the name of the constructor. * @param arity the number of fields in the constructor. + * @param builtinType true if constructor is annotated with @Builtin_Type, false otherwise. */ - case class Cons(name: String, arity: Int) + case class Cons(name: String, arity: Int, builtinType: Boolean = false) /** A representation of an imported polyglot symbol. * diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala index d2281cf31141..32495bad9ff6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala @@ -6,12 +6,8 @@ import org.enso.compiler.core.ir.MetadataStorage.ToPair import org.enso.compiler.data.BindingsMap import org.enso.compiler.data.BindingsMap.ModuleReference import org.enso.compiler.pass.IRPass -import org.enso.compiler.pass.desugar.{ - ComplexType, - FunctionBinding, - GenerateMethodBodies -} -import org.enso.compiler.pass.resolve.{MethodDefinitions, Patterns} +import org.enso.compiler.pass.desugar.{ComplexType, FunctionBinding, GenerateMethodBodies} +import org.enso.compiler.pass.resolve.{MethodDefinitions, ModuleAnnotations, Patterns} import scala.annotation.unused @@ -48,7 +44,11 @@ case object BindingAnalysis extends IRPass { ): IR.Module = { val definedConstructors = ir.bindings.collect { case cons: IR.Module.Scope.Definition.Atom => - BindingsMap.Cons(cons.name.name, cons.arguments.length) + // FIXME: move to a different pass + val isBuiltinType = cons + .getMetadata(ModuleAnnotations) + .exists(_.annotations.exists(_.name == "@Builtin_Type")) + BindingsMap.Cons(cons.name.name, cons.arguments.length, isBuiltinType) } val importedPolyglot = ir.imports.collect { case poly: IR.Module.Scope.Import.Polyglot => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala index 185758f5ca51..6005ef7ad390 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala @@ -114,7 +114,14 @@ case object ComplexType extends IRPass { .collect { case d: IR.Module.Scope.Definition.Atom => d } .map(atom => annotations - .map(ann => atom.updateMetadata(ModuleAnnotations -->> ann)) + .map(ann => { + + // Annotations of Atoms in Complex Types were being overwritten. We want to make sure that + // we only append the annotations of complex types without errasing the former. + // FIXME check if there is a nicer way of doing this + val old = atom.getMetadata(ModuleAnnotations).map(_.annotations).getOrElse(Nil) + atom.updateMetadata(ModuleAnnotations -->> ann.copy(ann.annotations ++ old)) + }) .getOrElse(atom) ) val atomIncludes = typ.body.collect { case n: IR.Name => n } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index d38ec8d1fc5f..b79f6a1beb7b 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -19,6 +19,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return success exit code (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "echo" Array.empty "" False False False @@ -32,6 +33,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return success exit code (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_1 "/c") "" False False False @@ -45,6 +47,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error when creating nonexistent command" in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array |main = System.create_process "nonexistentcommandxyz" Array.empty "" False False False |""".stripMargin @@ -57,6 +60,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error exit code (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "ls" (Array.new_1 "--gibberish") "" False False False @@ -71,6 +75,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error exit code (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "exit 7") "" False False False @@ -85,6 +90,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin chars (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; echo $line") "" True True True @@ -100,6 +106,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin chars (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "" True True True @@ -116,6 +123,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val input = Random.nextBytes(Byte.MaxValue) val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "wc -c") "" True True True @@ -131,6 +139,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin unused (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "echo" (Array.new_1 "42") "" True True True @@ -146,6 +155,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin unused (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -161,6 +171,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin empty (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "echo" (Array.new_1 "9") "" True True True @@ -175,6 +186,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin empty (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -189,6 +201,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "provide stdin string (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; printf $line") "hello" False False False @@ -203,6 +216,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "provide stdin string (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "hello" False False False @@ -217,6 +231,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout chars (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False True True @@ -231,6 +246,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout chars (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False True True @@ -245,6 +261,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout binary (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\x01\x0F\x10'") "" False True True @@ -259,6 +276,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stdout string (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False False False @@ -274,6 +292,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stdout string (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False False False @@ -289,6 +308,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr chars (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False True True @@ -303,6 +323,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr chars (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False True True @@ -317,6 +338,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr binary (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\xCA\xFE\xBA\xBE' 1>&2") "" False True True @@ -331,6 +353,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stderr string (Unix)" taggedAs OsUnix in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False False False @@ -345,6 +368,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stderr string (Windows)" taggedAs OsWindows in { val code = """from Standard.Builtins import all + |import Standard.Base.Data.Array | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False False False diff --git a/test/Tests/src/Data/Array_Spec.enso b/test/Tests/src/Data/Array_Spec.enso index 5effdecd8b83..0cb5c916d378 100644 --- a/test/Tests/src/Data/Array_Spec.enso +++ b/test/Tests/src/Data/Array_Spec.enso @@ -26,3 +26,5 @@ spec = Test.group "Arrays" <| Test.expect_panic_with (arr.at -1) Invalid_Array_Index_Error Test.expect_panic_with (arr.at 3) Invalid_Array_Index_Error Test.expect_panic_with (arr.set_at 3 100) Invalid_Array_Index_Error + +main = Test.Suite.run_main here.spec diff --git a/test/Tests/src/Semantic/Case_Spec.enso b/test/Tests/src/Semantic/Case_Spec.enso index 8402260df495..82a95330af0e 100644 --- a/test/Tests/src/Semantic/Case_Spec.enso +++ b/test/Tests/src/Semantic/Case_Spec.enso @@ -1,5 +1,4 @@ from Standard.Base import all -import Standard.Builtins import Standard.Test polyglot java import java.util.Random @@ -68,10 +67,10 @@ spec = Test.group "Pattern Matches" <| Test.specify "should be able to match on the Polyglot type" <| random_gen = Random.new case random_gen of - Builtins.Polyglot -> Nothing + Polyglot -> Nothing _ -> Test.fail "Expected a polyglot object to match." - case Builtins.Polyglot of - Builtins.Polyglot -> Nothing + case Polyglot of + Polyglot -> Nothing _ -> Test.fail "Expected the Polyglot constructor to match." Test.specify "should be able to match on the Any type" <| value_1 = 1.23143 @@ -82,9 +81,11 @@ spec = Test.group "Pattern Matches" <| case value_2 of Any -> Nothing _ -> Test.fail "Expected any value to match Any." - case Builtins.Polyglot of + case Polyglot of Any -> Nothing _ -> Test.fail "Expect any constructor to match Any." case Any of Any -> Nothing _ -> Test.fail "Expected the Any constructor to match." + +main = Test.Suite.run_main here.spec diff --git a/test/Tests/src/Semantic/Meta_Spec.enso b/test/Tests/src/Semantic/Meta_Spec.enso index 1ca122932d14..31745f04781b 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -1,7 +1,6 @@ from Standard.Base import all import Standard.Base.System.Platform from Standard.Base.Data.Text.Text_Sub_Range import Last -import Standard.Builtins import Standard.Test @@ -63,7 +62,7 @@ spec = Test.group "Meta-Value Manipulation" <| 1.0.is_a Text . should_be_false random_gen = Random.new - Meta.is_a random_gen Builtins.Polyglot . should_be_true + Meta.is_a random_gen Polyglot . should_be_true Meta.is_an random_gen Integer . should_be_false (My_Type 1 "foo" Nothing).is_a My_Type . should_be_true @@ -82,7 +81,7 @@ spec = Test.group "Meta-Value Manipulation" <| _ -> Nothing Test.specify "should allow to get the source location of a frame" pending=location_pending <| src = Meta.get_source_location 0 - loc = "Meta_Spec.enso:84:15-40" + loc = "Meta_Spec.enso:83:15-40" src.take (Last loc.length) . should_equal loc Test.specify "should allow to get qualified type names of values" <| @@ -94,3 +93,5 @@ spec = Test.group "Meta-Value Manipulation" <| Test.specify "should allow access to package names" <| Enso_Project.name.should_equal 'Tests' Base.enso_project.name.should_equal 'Base' + +main = Test.Suite.run_main here.spec From 02ab5b122c72133766b815f411d5e776ca826c01 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 4 Apr 2022 14:29:05 +0200 Subject: [PATCH 04/73] Move Ref type + basic test --- .../native/inc/error_preprocessor.enso | 6 +-- .../Standard/Base/0.0.0-dev/src/Data/Ref.enso | 45 +++++++++++++++++++ .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 + .../interpreter/runtime/builtin/Mutable.java | 8 +--- .../runtime/src/main/resources/Builtins.enso | 44 ------------------ test/Tests/src/Data/Ref_Spec.enso | 12 +++++ 6 files changed, 64 insertions(+), 53 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso create mode 100644 test/Tests/src/Data/Ref_Spec.enso diff --git a/app/gui/view/graph-editor/src/builtin/visualization/native/inc/error_preprocessor.enso b/app/gui/view/graph-editor/src/builtin/visualization/native/inc/error_preprocessor.enso index 0ad3db37269f..67f34939cc39 100644 --- a/app/gui/view/graph-editor/src/builtin/visualization/native/inc/error_preprocessor.enso +++ b/app/gui/view/graph-editor/src/builtin/visualization/native/inc/error_preprocessor.enso @@ -1,7 +1,7 @@ x -> - result = Builtins.Ref.new '{ message: ""}' + result = Ref.new '{ message: ""}' x.catch err-> message = err.to_display_text - Builtins.Ref.put result ('{ "kind": "Dataflow", "message": ' + message.to_json.to_text + '}') - Builtins.Ref.get result + Ref.put result ('{ "kind": "Dataflow", "message": ' + message.to_json.to_text + '}') + Ref.get result diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso new file mode 100644 index 000000000000..3a33e7fa294b --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso @@ -0,0 +1,45 @@ +## Utilities for working with mutable references. +type Ref + + ## A mutable reference type. + @Builtin_Type + type Ref + +## FIXME consider moving this as methods of Ref, currently a lot of stuff depends +## on the current design +## Gets the contents of the mutable reference ref. + + Arguments: + - ref: The reference to get the contents of. + + > Example + Getting the contents of a reference. + + Ref.get (Ref.new 0) +get : Ref -> Any +get ref = @Builtin_Method "Ref.get" + +## Puts a new value into the reference, returning the old value. + + Arguments: + - ref: The reference in which to store the value. + - new_value: The new value to store in ref. + + > Example + Storing the value 10 in a reference. + + Ref.put (Ref.new 0) 10 +put : Ref -> Any -> Any +put ref new_value = @Builtin_Method "Ref.put" + +## Creates a new reference containing the provided value. + + Arguments: + - value: The value to be contained in the ref. + + > Example + Creating a new reference containing the value 7. + + Ref.new 7 +new : Any -> Ref +new value = @Builtin_Method "Ref.new" \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index c269fc34714c..3b54d22dca84 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -12,6 +12,7 @@ import project.Data.Ordering import project.Data.Ordering.Sort_Order import project.Data.Pair import project.Data.Range +import project.Data.Ref import project.Data.Text.Extensions import project.Data.Text.Matching import project.Data.Vector @@ -53,6 +54,7 @@ from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise from project.Data.Pair export Pair from project.Data.Range export Range +from project.Data.Ref export Ref ## TODO [RW] Once autoscoping is implemented or automatic imports for ADTs are fixed in the IDE, we should revisit if we want to export ADTs like `Case` by default. It may be unnecessary pollution of scope, but until the issues are diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java index fd41fe9a1036..a88e97e97d63 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java @@ -19,13 +19,9 @@ public class Mutable { */ public Mutable(Builtins builtins, Language language, ModuleScope scope) { array = null; + ref = null; this.builtins = builtins; - ref = new AtomConstructor("Ref", scope).initializeFields(); - scope.registerConstructor(ref); - scope.registerMethod(ref, "new", NewRefMethodGen.makeFunction(language)); - scope.registerMethod(ref, "get", GetRefMethodGen.makeFunction(language)); - scope.registerMethod(ref, "put", PutRefMethodGen.makeFunction(language)); } /** @return the Array constructor. */ @@ -35,6 +31,6 @@ public AtomConstructor array() { /** @return the Ref constructor. */ public AtomConstructor ref() { - return ref; + return builtins.getBuiltinType("Ref"); } } diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 003c39ffe336..89a58b6c392c 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -741,50 +741,6 @@ type Meta get_qualified_type_name : Any -> Text get_qualified_type_name value = @Builtin_Method "Meta.get_qualified_type_name" -## Utilities for working with mutable references. -type Ref - - ## A mutable reference type. - @Builtin_Type - type Ref - - ## Creates a new reference containing the provided value. - - Arguments: - - value: The value to be contained in the ref. - - > Example - Creating a new reference containing the value 7. - - Ref.new 7 - new : Any -> Ref - new value = @Builtin_Method "Ref.new" - - ## Gets the contents of the mutable reference ref. - - Arguments: - - ref: The reference to get the contents of. - - > Example - Getting the contents of a reference. - - Ref.get (Ref.new 0) - get : Ref -> Any - get ref = @Builtin_Method "Ref.get" - - ## Puts a new value into the reference, returning the old value. - - Arguments: - - ref: The reference in which to store the value. - - new_value: The new value to store in ref. - - > Example - Storing the value 10 in a reference. - - Ref.put (Ref.new 0) 10 - put : Ref -> Any -> Any - put ref new_value = @Builtin_Method "Ref.put" - ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or diff --git a/test/Tests/src/Data/Ref_Spec.enso b/test/Tests/src/Data/Ref_Spec.enso new file mode 100644 index 000000000000..3f543e59f01b --- /dev/null +++ b/test/Tests/src/Data/Ref_Spec.enso @@ -0,0 +1,12 @@ +from Standard.Base import all + +import Standard.Test + +spec = Test.group "Refs" <| + Test.specify "should be able to store and retrieve value in references" <| + r = Ref.new 'foo' + Ref.put r 'bar' + v = Ref.get r + v.should_equal 'bar' + +main = Test.Suite.run_main here.spec From 6938b2d8b40f3af4f9a950682ec1c9104179b95f Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 5 Apr 2022 17:00:14 +0200 Subject: [PATCH 05/73] Move Boolean out of Builtins to std library A very simple move of Boolean values to std library. Initially wanted to also fix the type definition of Boolean so that it looks like ``` @Builtin_Type type Boolean type True type False ... methods ``` rather than current type Boolean @Builtin_Type type Builtin_Type ... methods @Builtin_Type type True @Builtin_Type type False ``` but turns out this is a bigger task on its own. For example ComplexTypes pass would have to keep the information Boolean data type, rather than erasing it. --- .../Base/0.0.0-dev/src/Data/Boolean.enso | 131 ++++++++++++++++++ .../Base/0.0.0-dev/src/Data/List.enso | 1 + .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../interpreter/runtime/builtin/Bool.java | 17 ++- .../interpreter/runtime/builtin/Builtins.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 115 --------------- .../enso/compiler/codegen/IrToTruffle.scala | 6 +- .../test/semantic/ConstructorsTest.scala | 1 + .../interpreter/test/semantic/EvalTest.scala | 2 + .../test/semantic/GlobalScopeTest.scala | 1 + .../test/semantic/SystemProcessTest.scala | 25 ++++ .../scala/org/enso/std/test/BooleanTest.scala | 7 + .../scala/org/enso/std/test/NumberTest.scala | 3 +- 13 files changed, 190 insertions(+), 125 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso new file mode 100644 index 000000000000..adeb64f37d69 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso @@ -0,0 +1,131 @@ +## Booleans. +type Boolean + + ## A type with only two possible values. FIXME REMOVE? + + The boolean type represents the two truth values of boolean logic. It is + primarily used for control-flow. + @Builtin_Type + type Boolean + + ## Compares two booleans for equality. + + Arguments: + - that: The boolean to compare this with. + + > Example + Comparing True to False to get False. + + True == False + == : Boolean -> Boolean + == that = @Builtin_Method "Boolean.==" + + ## Computes the logical and (conjunction) of two booleans. + + Arguments: + - that: The boolean to compute the conjunction of this with. + + ! Short Circuiting + This method is not implemented in a short-circuiting manner. This means + that even if this is False, it will also evaluate that. This is + for performance. + + > Example + Computing the conjunction of False and True (to get False). + + False && True + && : Boolean -> Boolean + && that = @Builtin_Method "Boolean.&&" + + ## Computes the logical or (disjunction) of two booleans. + + Arguments: + - that: The boolean to compute the disjunction of this with. + + ! Short Circuiting + This method is not implemented in a short-circuiting manner. This means + that even if this is True, it will also evaluate that. This is + for performance. + + > Example + Computing the disjunction of True and False (to get True). + + True || False + || : Boolean -> Boolean + || that = @Builtin_Method "Boolean.||" + + ## Compares two booleans and returns an ordering value. + + Arguments: + - that: The boolean to compare with the value of this. + + ! Short Circuiting + This method is not implemented in a short-circuiting manner. This means + that even if this is False, it will also evaluate that. This is + for performance. + + > Example + Computing the ordering of True and False (to get Greater). + + True.compare_to False + compare_to : Boolean -> Ordering + compare_to that = @Builtin_Method "Boolean.compare_to" + + ## Computes the logical negation of this. + + > Example + Negating True to get False. + + True.not + not : Boolean + not = @Builtin_Method "Boolean.not" + + ## Generates a human-readable text representation of the boolean. + + > Example + Converting the value True to text. + + True.to_text + to_text : Text + to_text = @Builtin_Method "Boolean.to_text" + +## The if-then-else control flow operator that executes one of two branches + based on a conditional. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + - on_false: The computation to evaluate if this evaluates to False. + + Both of the arguments to this method are _lazy_, meaning that they will + only be evaluated if they are needed (based on the condition). + + > Example + Telling the user if a number 27 is divisible by three. + + if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" +if_then_else : Any -> Any -> Any +if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" + +## The if-then control flow operator that executes a branch if the condition + is true, and otherwise returns Nothing. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + + The argument to this method is _lazy_, meaning that it will only be + evaluated if the this evaluates to True. + + > Example + Printing a message to the user only if a number is divisible by three. + + if (27 % 3) == 0 then IO.println "Fizz" +if_then : Any -> Any | Nothing +if_then ~on_true = @Builtin_Method "Boolean.if_then" + +## The constructor for the value True. +@Builtin_Type +type True + +## The constructor for the value False. +@Builtin_Type +type False diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index f28e03968131..87a117c61799 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,5 +1,6 @@ from Standard.Builtins import all from Standard.Builtins export Nil, Cons +from Standard.Base.Data.Boolean import all ## The basic cons-list type. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 3b54d22dca84..c20fb8ec54fb 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -1,3 +1,4 @@ +import project.Data.Boolean import project.Data.Any.Extensions import project.Data.Array import project.Data.Interval @@ -29,7 +30,7 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Any, True, False, Cons, Boolean, Arithmetic_Error +from Standard.Builtins import Nothing, Number, Integer, Any, Cons, Arithmetic_Error export project.Data.Interval export project.Data.Json @@ -47,6 +48,7 @@ export project.System.File export project.Data.Text.Regex.Mode as Regex_Mode export project.Warning +from project.Data.Boolean export all from project.Data.Array export Array from project.Data.Any.Extensions export all from project.Data.List export Nil, Cons diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java index dd5cdf2be930..8e353a2ee1da 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java @@ -10,6 +10,7 @@ public class Bool { private final AtomConstructor tru; private final AtomConstructor fls; private final AtomConstructor bool; + private final Builtins builtins; /** * Creates and registers all the boolean constructors. @@ -17,8 +18,12 @@ public class Bool { * @param language the current language instance. * @param scope the scope to register constructors and methods in. */ - public Bool(Language language, ModuleScope scope) { - bool = new AtomConstructor("Boolean", scope).initializeFields(); + public Bool(Builtins builtins, Language language, ModuleScope scope) { + this.builtins = builtins; + tru = null; + fls = null; + bool = null; + /*bool = new AtomConstructor("Boolean", scope).initializeFields(); scope.registerConstructor(bool); scope.registerMethod(bool, "if_then_else", IfThenElseMethodGen.makeFunction(language)); scope.registerMethod(bool, "if_then", IfThenMethodGen.makeFunction(language)); @@ -31,21 +36,21 @@ public Bool(Language language, ModuleScope scope) { tru = new AtomConstructor("True", scope).initializeFields(); scope.registerConstructor(tru); fls = new AtomConstructor("False", scope).initializeFields(); - scope.registerConstructor(fls); + scope.registerConstructor(fls);*/ } /** @return the atom constructor for {@code True}. */ public AtomConstructor getTrue() { - return tru; + return builtins.getBuiltinType("True"); } /** @return the atom constructor for {@code False}. */ public AtomConstructor getFalse() { - return fls; + return builtins.getBuiltinType("False"); } /** @return the atom constructor for {@code Boolean}. */ public AtomConstructor getBool() { - return bool; + return builtins.getBuiltinType("Boolean"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index bcfea9020eb9..c4178be871e0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -109,7 +109,7 @@ public Builtins(Context context) { builtinTypes = new HashMap<>(); any = new AtomConstructor("Any", scope).initializeFields(); - bool = new Bool(language, scope); + bool = new Bool(this, language, scope); debug = new AtomConstructor("Debug", scope).initializeFields(); dataflowError = new DataflowError(language, scope); Warning.initWarningMethods(language, scope); diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 89a58b6c392c..52fc23c48d0c 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -4,121 +4,6 @@ # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. -## Booleans. -type Boolean - - ## A type with only two possible values. - - The boolean type represents the two truth values of boolean logic. It is - primarily used for control-flow. - @Builtin_Type - type Boolean - - ## Compares two booleans for equality. - - Arguments: - - that: The boolean to compare this with. - - > Example - Comparing True to False to get False. - - True == False - == : Boolean -> Boolean - == that = @Builtin_Method "Boolean.==" - - ## Computes the logical and (conjunction) of two booleans. - - Arguments: - - that: The boolean to compute the conjunction of this with. - - ! Short Circuiting - This method is not implemented in a short-circuiting manner. This means - that even if this is False, it will also evaluate that. This is - for performance. - - > Example - Computing the conjunction of False and True (to get False). - - False && True - && : Boolean -> Boolean - && that = @Builtin_Method "Boolean.&&" - - ## Computes the logical or (disjunction) of two booleans. - - Arguments: - - that: The boolean to compute the disjunction of this with. - - ! Short Circuiting - This methid is not implemented in a short-circuiting manner. This means - that even if this is True, it will also evaluate that. This is - for performance. - - > Example - Computing the disjunction of True and False (to get True). - - True || False - || : Boolean -> Boolean - || that = @Builtin_Method "Boolean.||" - - ## Computes the logical negation of this. - - > Example - Negating True to get False. - - True.not - not : Boolean - not = @Builtin_Method "Boolean.not" - - ## Generates a human-readable text representation of the boolean. - - > Example - Converting the value True to text. - - True.to_text - to_text : Text - to_text = @Builtin_Method "Boolean.to_text" - - ## The if-then-else control flow operator that executes one of two branches - based on a conditional. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - on_false: The computation to evaluate if this evaluates to False. - - Both of the arguments to this method are _lazy_, meaning that they will - only be evaluated if they are needed (based on the condition). - - > Example - Telling the user if a number 27 is divisible by three. - - if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" - if_then_else : Any -> Any -> Any - if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - - ## The if-then control flow operator that executes a branch if the condition - is true, and otherwise returns Nothing. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - The argument to this method is _lazy_, meaning that it will only be - evaluated if the this evaluates to True. - - > Example - Printing a message to the user only if a number is divisible by three. - - if (27 % 3) == 0 then IO.println "Fizz" - if_then : Any -> Any | Nothing - if_then ~on_true = @Builtin_Method "Boolean.if_then" - -## The constructor for the value True. -@Builtin_Type -type True - -## The constructor for the value False. -@Builtin_Type -type False - ## Debug utilities. type Debug diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index d4fff69d4954..468a6cda39a1 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -1,6 +1,6 @@ package org.enso.compiler.codegen -import com.oracle.truffle.api.Truffle +import com.oracle.truffle.api.{RootCallTarget, Truffle} import com.oracle.truffle.api.frame.FrameSlot import com.oracle.truffle.api.source.{Source, SourceSection} import org.enso.compiler.core.IR @@ -36,6 +36,7 @@ import org.enso.interpreter.{Constants, Language} import java.math.BigInteger import org.enso.compiler.core.IR.Name.Special +import org.enso.interpreter.runtime.builtin.Bool import org.enso.pkg.QualifiedName import scala.collection.{immutable, mutable} @@ -855,6 +856,9 @@ class IrToTruffle( // (array: AtomConstructor, branch: RootCallTarget) -> BranchNode // and related eta-expansion appear to crash Graal (not a joke). private val branchNodeFactories: Map[(QualifiedName, String), BranchNodeFactory] = immutable.HashMap[(QualifiedName, String), BranchNodeFactory]( + (QualifiedName(List("Standard", "Base"), "Boolean"), "True") -> { case (_: AtomConstructor, target: RootCallTarget) => BooleanBranchNode.build(true, target)}, + (QualifiedName(List("Standard", "Base"), "Boolean"), "False") -> { case (_: AtomConstructor, target: RootCallTarget) => BooleanBranchNode.build(false, target)}, + (QualifiedName(List("Standard", "Base"), "Boolean"), "Boolean") -> { case (bool: AtomConstructor, target: RootCallTarget) => BooleanConstructorBranchNode.build(bool.asInstanceOf[Bool], target)}, (QualifiedName(List("Standard", "Base"), "Polyglot"), "Polyglot") -> PolyglotBranchNode.build _, (QualifiedName(List("Standard", "Base", "Data"), "Array"), "Array") -> ArrayBranchNode.build _, ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index 307150a5f9a1..cb63431f9f2e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala @@ -29,6 +29,7 @@ class ConstructorsTest extends InterpreterTest { "work with recursion" in { val testCode = """from Standard.Builtins import all + |from Standard.Base import all | |main = | genList = i -> if i == 0 then Nil else Cons i (genList (i - 1)) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala index 1baa0c0766c4..8d18ee864e29 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala @@ -66,6 +66,7 @@ class EvalTest extends InterpreterTest { "work in a recursive setting" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | fn = sumTo -> @@ -80,6 +81,7 @@ class EvalTest extends InterpreterTest { "work inside a thunk passed to another function" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | fn = sumTo -> diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala index 4da75318f52f..8b9755c92d21 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala @@ -59,6 +59,7 @@ class GlobalScopeTest extends InterpreterTest { "be able to mutually recurse in the global scope" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |Nothing.decrementCall = number -> | res = number - 1 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index b79f6a1beb7b..5a38feae769e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -20,6 +20,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" Array.empty "" False False False @@ -34,6 +35,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_1 "/c") "" False False False @@ -48,6 +50,8 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all + | |main = System.create_process "nonexistentcommandxyz" Array.empty "" False False False |""".stripMargin @@ -61,6 +65,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "ls" (Array.new_1 "--gibberish") "" False False False @@ -76,6 +81,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "exit 7") "" False False False @@ -91,6 +97,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; echo $line") "" True True True @@ -107,6 +114,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "" True True True @@ -124,6 +132,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "wc -c") "" True True True @@ -140,6 +149,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "42") "" True True True @@ -156,6 +166,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -172,6 +183,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "9") "" True True True @@ -187,6 +199,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -202,6 +215,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; printf $line") "hello" False False False @@ -217,6 +231,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "hello" False False False @@ -232,6 +247,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False True True @@ -247,6 +263,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False True True @@ -262,6 +279,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\x01\x0F\x10'") "" False True True @@ -277,6 +295,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False False False @@ -293,6 +312,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False False False @@ -309,6 +329,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False True True @@ -324,6 +345,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False True True @@ -339,6 +361,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\xCA\xFE\xBA\xBE' 1>&2") "" False True True @@ -354,6 +377,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False False False @@ -369,6 +393,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False False False diff --git a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala index 71f9058381f6..b03ab174eda9 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala @@ -12,6 +12,7 @@ class BooleanTest extends InterpreterTest { "support if_then_else" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | if True then IO.println "true when true" else IO.println "false when true" @@ -24,6 +25,7 @@ class BooleanTest extends InterpreterTest { "support overriding methods on boolean" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |Boolean.isTrue = this | @@ -40,6 +42,7 @@ class BooleanTest extends InterpreterTest { "support pattern matching" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |to_num b = case b of | True -> 1 @@ -55,6 +58,7 @@ class BooleanTest extends InterpreterTest { "support per-constructor method overloads" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |True.to_num = 1 |False.to_num = 2 @@ -67,6 +71,7 @@ class BooleanTest extends InterpreterTest { "support per-single-constructor method overloads" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |Boolean.to_num = 2 |True.to_num = 1 @@ -79,6 +84,7 @@ class BooleanTest extends InterpreterTest { "support logical AND and OR operators" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | IO.println True&&False @@ -94,6 +100,7 @@ class BooleanTest extends InterpreterTest { "support negation" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | IO.println True.not diff --git a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala index 6887c1c06df5..6743362469c4 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala @@ -11,6 +11,7 @@ class NumberTest extends InterpreterTest { "support equality comparisons" in { val code = """from Standard.Builtins import all + |from Standard.Base import all | |main = | IO.println 7==5 @@ -22,7 +23,7 @@ class NumberTest extends InterpreterTest { "support a recursive sum case" in { val code = - """ + """from Standard.Base import all |main = sumTo -> | summator = acc -> current -> | if current == 0 then acc else summator acc+current current-1 From 75cd43d2465c5f811e3ac7a9d0c457bf0e1513cc Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 6 Apr 2022 17:43:16 +0200 Subject: [PATCH 06/73] Drop reflection requirement for builtin methods Per PR review: using `reflections` library adds an unnecessary cost at startup. Instead, while generating code from the BuiltinMethod annotations, we write meta files that can be read at compile time, therefore avoiding the performance penalty. --- build.sbt | 3 +- .../builtin/special/JoinThreadNode.java | 2 +- .../builtin/special/NewRefNode.java | 2 +- .../builtin/special/ReadRefNode.java | 2 +- .../builtin/special/RunThreadNode.java | 2 +- .../builtin/special/WriteRefNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 134 +++++++++++++----- .../enso/interpreter/dsl/MethodProcessor.java | 16 +++ .../dsl/model/MethodDefinition.java | 7 + 9 files changed, 124 insertions(+), 46 deletions(-) diff --git a/build.sbt b/build.sbt index e5c50a3ae80b..217832da9d05 100644 --- a/build.sbt +++ b/build.sbt @@ -1147,8 +1147,7 @@ lazy val runtime = (project in file("engine/runtime")) "org.scalatest" %% "scalatest" % scalatestVersion % Test, "org.graalvm.truffle" % "truffle-api" % graalVersion % Benchmark, "org.typelevel" %% "cats-core" % catsVersion, - "eu.timepit" %% "refined" % refinedVersion, - "org.reflections" % "reflections" % "0.10.2" + "eu.timepit" %% "refined" % refinedVersion ), // Note [Unmanaged Classpath] Compile / unmanagedClasspath += (`core-definition` / Compile / packageBin).value, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/JoinThreadNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/JoinThreadNode.java index 1ad915a8f4e9..2d2d8bc31c6d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/JoinThreadNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/JoinThreadNode.java @@ -3,7 +3,7 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; -@BuiltinMethod(type = "", name = "") +@BuiltinMethod(type = "Special", name = "") public class JoinThreadNode extends Node { public Object execute(Object thread) { try { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/NewRefNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/NewRefNode.java index e62f85486705..ca6898cc793b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/NewRefNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/NewRefNode.java @@ -4,7 +4,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.data.Ref; -@BuiltinMethod(type = "", name = "") +@BuiltinMethod(type = "Special", name = "") public class NewRefNode extends Node { public Ref execute() { return new Ref(null); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/ReadRefNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/ReadRefNode.java index a4912673d1e8..0046fea003d2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/ReadRefNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/ReadRefNode.java @@ -4,7 +4,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.data.Ref; -@BuiltinMethod(type = "", name = "") +@BuiltinMethod(type = "Special", name = "") public class ReadRefNode extends Node { public Object execute(Ref ref) { return ref.getValue(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/RunThreadNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/RunThreadNode.java index 5690d22df7cc..273b764f43ef 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/RunThreadNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/RunThreadNode.java @@ -10,7 +10,7 @@ import org.enso.interpreter.node.callable.thunk.ThunkExecutorNodeGen; import org.enso.interpreter.runtime.Context; -@BuiltinMethod(type = "", name = "") +@BuiltinMethod(type = "Special", name = "") public abstract class RunThreadNode extends Node { static RunThreadNode build() { return RunThreadNodeGen.create(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/WriteRefNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/WriteRefNode.java index ee457e4c7986..c27fb2210cce 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/WriteRefNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/special/WriteRefNode.java @@ -4,7 +4,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.data.Ref; -@BuiltinMethod(type = "", name = "") +@BuiltinMethod(type = "Special", name = "") public class WriteRefNode extends Node { public Object execute(Ref ref, Object value) { ref.setValue(value); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index c4178be871e0..c0e03d8b976f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -1,17 +1,21 @@ package org.enso.interpreter.runtime.builtin; import com.oracle.truffle.api.CompilerDirectives; + import java.io.IOException; import java.lang.reflect.Method; +import java.net.URI; import java.nio.charset.StandardCharsets; +import java.nio.file.*; import java.util.*; +import java.util.stream.Stream; -import com.oracle.truffle.api.nodes.NodeInfo; import org.enso.compiler.Passes; import org.enso.compiler.context.FreshNameSupply; import org.enso.compiler.exception.CompilerError; import org.enso.compiler.phase.BuiltinsIrBuilder; import org.enso.interpreter.Language; +import org.enso.interpreter.dsl.model.MethodDefinition; import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; @@ -21,10 +25,6 @@ import org.enso.interpreter.node.expression.builtin.error.GetAttachedStackTraceMethodGen; import org.enso.interpreter.node.expression.builtin.error.ThrowPanicMethodGen; import org.enso.interpreter.node.expression.builtin.function.ExplicitCallFunctionMethodGen; -import org.enso.interpreter.node.expression.builtin.interop.generic.GetMemberMethodGen; -import org.enso.interpreter.node.expression.builtin.interop.generic.IsLanguageInstalledMethodGen; -import org.enso.interpreter.node.expression.builtin.interop.java.AddToClassPathMethodGen; -import org.enso.interpreter.node.expression.builtin.interop.java.LookupClassMethodGen; import org.enso.interpreter.node.expression.builtin.io.GetCwdMethodGen; import org.enso.interpreter.node.expression.builtin.io.GetFileMethodGen; import org.enso.interpreter.node.expression.builtin.io.GetUserHomeMethodGen; @@ -52,9 +52,6 @@ import org.enso.interpreter.runtime.type.Constants; import org.enso.pkg.QualifiedName; -import org.reflections.Reflections; -import org.reflections.scanners.Scanners; - /** Container class for static predefined atoms, methods, and their containing scope. */ public class Builtins { public static final String PACKAGE_NAME = "Builtins"; @@ -209,7 +206,7 @@ public Builtins(Context context) { thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); - readAllBuiltinNodes(scope); + readBuiltinsMetadata(scope); } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ @@ -250,39 +247,98 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } } - @CompilerDirectives.TruffleBoundary - public void readAllBuiltinNodes(ModuleScope scope) { - Reflections reflections = new Reflections("org.enso.interpreter.node.expression.builtin"); - Set subtypes = reflections.get(Scanners.SubTypes.of(Scanners.TypesAnnotated.with(NodeInfo.class))); - subtypes.stream().forEach(className -> { + private void readBuiltinsMetadata(ModuleScope scope) { + ClassLoader classLoader = getClass().getClassLoader(); + FileSystem fs = null; + Stream builtinMetaPath; + try { + URI resource = classLoader.getResource(MethodDefinition.META_PATH).toURI(); + fs = initFileSystem(resource); + builtinMetaPath = Files.walk(Paths.get(resource)).flatMap(p -> acceptFiles(p)); + } catch (Exception ioe) { + ioe.printStackTrace(); + builtinMetaPath = Stream.empty(); + } + builtinMetaPath.forEach(metaPath -> { + List lines; try { - Class clazz = (Class) Class.forName(className); - NodeInfo info = clazz.getDeclaredAnnotation(NodeInfo.class); - String[] name = info.shortName().split("\\."); - if (name.length == 2 && !name[0].isEmpty()) { - scope.getLocalConstructor(name[0]).ifPresentOrElse(constr -> { - Map> atomNodes = builtinNodes.get(name[0]); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - builtinNodes.put(constr.getName(), atomNodes); - } - atomNodes.put(name[1], clazz); - }, () -> { - Map> atomNodes = builtinNodes.get(name[0]); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - builtinNodes.put(name[0], atomNodes); - } - atomNodes.put(name[1], clazz); - }); - } - } catch (Exception e) { - throw new CompilerError(e.getMessage()); + lines = Files.readAllLines(metaPath, StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + lines = new ArrayList<>(); } - // todo: handle gracefully other cases + lines.forEach(line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length != 2) { + throw new CompilerError("Invalid builtin metadata in " + metaPath + ": " + line); + } + String[] builtinName = builtinMeta[0].split("\\."); + if (builtinName.length != 2) { + throw new CompilerError("Invalid builtin metadata in " + metaPath + ": " + line); + } + try { + Class clazz = (Class) Class.forName(builtinMeta[1]); + String builtinMethodOwner = builtinName[0]; + String builtinMethodName = builtinName[1]; + scope.getLocalConstructor(builtinMethodOwner).ifPresentOrElse(constr -> { + Map> atomNodes = builtinNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + builtinNodes.put(constr.getName(), atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }, () -> { + Map> atomNodes = builtinNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + builtinNodes.put(builtinMethodOwner, atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + }); }); + if (fs != null) { + try { + fs.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private FileSystem initFileSystem(URI uri) throws IOException + { + // Returning null ensures that we use the default one and at the same time we don't attempt + // to close it. + try { + FileSystems.getFileSystem(uri); + return null; + } catch (IllegalArgumentException iae) { + // file: schema doesn't like non-/ path but that's fine, it means the default file system is already setup + return null; + } catch (FileSystemNotFoundException e) { + Map env = new HashMap<>(); + env.put("create", "true"); + return FileSystems.newFileSystem(uri, env); + } + } + + private Stream acceptFiles(Path path) { + if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(".builtin")) { + return Stream.of(path); + } else if (Files.isDirectory(path)) { + try { + return Files.walk(path).flatMap(p -> {if (p != path) return acceptFiles(p); else return Stream.empty();}); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + return Stream.empty(); } public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index 5395d8b64ded..9e50d59bc876 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -11,6 +11,8 @@ import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; +import javax.tools.FileObject; +import javax.tools.StandardLocation; import java.io.IOException; import java.io.PrintWriter; import java.util.*; @@ -61,6 +63,7 @@ public boolean process(Set annotations, RoundEnvironment } try { generateCode(def); + registerBuiltinMethod(def, element); } catch (IOException e) { e.printStackTrace(); } @@ -91,6 +94,19 @@ public boolean process(Set annotations, RoundEnvironment "org.enso.interpreter.runtime.state.Stateful", "org.enso.interpreter.runtime.type.TypesGen"); + private void registerBuiltinMethod(MethodDefinition methodDefinition, Element element) throws IOException { + String tpe = methodDefinition.getType().toLowerCase(); + if (tpe.isEmpty()) { + throw new InternalError("Type of the BuiltinMethod cannot be empty"); + } + FileObject res = processingEnv.getFiler().createResource( + StandardLocation.CLASS_OUTPUT, "", + MethodDefinition.META_PATH + "/" + tpe + "/" + methodDefinition.getClassName() + ".builtin", element + ); + String fullClassName = methodDefinition.getPackageName() + "." + methodDefinition.getClassName(); + res.openWriter().append(methodDefinition.getDeclaredName() + ":" + fullClassName+"\n").close(); + } + private void generateCode(MethodDefinition methodDefinition) throws IOException { JavaFileObject gen = processingEnv.getFiler().createSourceFile(methodDefinition.getQualifiedName()); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index b1cb9b5122b1..c9bde381f332 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -12,6 +12,8 @@ /** A domain-specific representation of a builtin method. */ public class MethodDefinition { private static final String STATEFUL = "org.enso.interpreter.runtime.state.Stateful"; + public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; + public static final String META_PATH = "META-INF" + "/" + NODE_PKG.replace('.', '/'); private final String packageName; private final String originalClassName; @@ -138,6 +140,11 @@ public String getDeclaredName() { return annotation.type() + "." + annotation.name(); } + /** @return the language-level owner type of this method. */ + public String getType() { + return annotation.type(); + } + /** @return get the description of this method. */ public String getDescription() { return annotation.description(); From 0f89f4421b05d8e5ea493bbaabb7b6ea63ab4e20 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 6 Apr 2022 18:06:39 +0200 Subject: [PATCH 07/73] Use constant values to avoid typos --- .../java/org/enso/interpreter/runtime/builtin/Builtins.java | 2 +- .../src/main/java/org/enso/interpreter/dsl/MethodProcessor.java | 2 +- .../java/org/enso/interpreter/dsl/model/MethodDefinition.java | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index c0e03d8b976f..3444e656fa12 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -329,7 +329,7 @@ private FileSystem initFileSystem(URI uri) throws IOException } private Stream acceptFiles(Path path) { - if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(".builtin")) { + if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(MethodDefinition.META_BUILTIN_EXTENSION)) { return Stream.of(path); } else if (Files.isDirectory(path)) { try { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index 9e50d59bc876..a899f3c78463 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -101,7 +101,7 @@ private void registerBuiltinMethod(MethodDefinition methodDefinition, Element el } FileObject res = processingEnv.getFiler().createResource( StandardLocation.CLASS_OUTPUT, "", - MethodDefinition.META_PATH + "/" + tpe + "/" + methodDefinition.getClassName() + ".builtin", element + MethodDefinition.META_PATH + "/" + tpe + "/" + methodDefinition.getClassName() + MethodDefinition.META_BUILTIN_EXTENSION, element ); String fullClassName = methodDefinition.getPackageName() + "." + methodDefinition.getClassName(); res.openWriter().append(methodDefinition.getDeclaredName() + ":" + fullClassName+"\n").close(); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index c9bde381f332..0a9393be24ad 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -14,6 +14,7 @@ public class MethodDefinition { private static final String STATEFUL = "org.enso.interpreter.runtime.state.Stateful"; public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; public static final String META_PATH = "META-INF" + "/" + NODE_PKG.replace('.', '/'); + public static final String META_BUILTIN_EXTENSION = ".builtin"; private final String packageName; private final String originalClassName; From 91c64320db28f0d6611488a82dcd957fa83eefec Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 7 Apr 2022 12:48:50 +0200 Subject: [PATCH 08/73] Move Meta out of builtins Demonstrates support for @BuiltinMethod when we are not dealing with special types known to the compiler. --- .../Base/0.0.0-dev/src/Error/Extensions.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 408 ++++++++++++------ .../builtin/meta/GetSourceLocationNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 12 +- .../interpreter/runtime/builtin/Meta.java | 59 --- .../runtime/src/main/resources/Builtins.enso | 184 -------- 7 files changed, 282 insertions(+), 387 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso index 8c1d639ef3e7..6ba7f3d239df 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso @@ -221,7 +221,7 @@ Caught_Panic.stack_trace = Panic.catch : Any -> Any -> (Caught_Panic -> Any) -> Any Panic.catch panic_type ~action handler = Panic.catch_primitive action caught_panic-> - case Builtins.Meta.get_polyglot_language panic_type == "java" of + case Meta.get_polyglot_language panic_type == "java" of False -> case caught_panic.payload.is_a panic_type of True -> handler caught_panic False -> Panic.throw caught_panic diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index c20fb8ec54fb..0ad2bcf61c39 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -72,4 +72,4 @@ from project.Meta.Enso_Project export all from project.Polyglot export all from project.Runtime.Extensions export all -from Standard.Builtins export all hiding Meta, Less, Equal, Greater, Ordering +from Standard.Builtins export all hiding Less, Equal, Greater, Ordering diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso index 52919c6bfcc9..836a12680e11 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso @@ -1,6 +1,235 @@ from Standard.Base import all -import Standard.Builtins +from Standard.Builtins import Any + +## UNSTABLE + ADVANCED + + A meta-representation of a runtime value. + + ! Warning + The functionality contained in this module exposes certain implementation + details of the language. As such, the API has no stability guarantees and + is subject to change as the Enso interpreter evolves. +type Meta + + ## UNSTABLE + ADVANCED + + An Atom meta-representation. + + Arguments: + - value: The value of the atom in the meta representation. + type Atom value + + ## UNSTABLE + ADVANCED + + A constructor meta-representation. + + Arguments: + - value: The value of the constructor in the meta representation. + type Constructor value + + ## UNSTABLE + ADVANCED + + A primitive value meta-prepresentation. + + Arguments: + - value: The value of the primitive object in the meta representation. + type Primitive value + + ## UNSTABLE + ADVANCED + + An unresolved symbol meta-representation. + + Arguments: + - value: The value of the unresolved symbol in the meta representation. + type Unresolved_Symbol value + + ## UNSTABLE + ADVANCED + + An error meta-representation, containing the payload of a dataflow error. + + Arguments: + - value: The payload of the error. + type Error value + + ## UNSTABLE + ADVANCED + + A polyglot value meta-representation. + + Arguments: + - value: The polyglot value contained in the meta representation. + type Polyglot value + + +## Atom methods +## PRIVATE + + Gets the atom constructor instance for the provided atom. + + Arguments: + - atom: The atom to obtain the constructor for. +get_atom_constructor : Atom -> Atom_Constructor +get_atom_constructor atom = @Builtin_Method "Meta.get_atom_constructor" + +## PRIVATE + + Get the fields for the provided atom. + + Arguments: + - atom: The atom to obtain the fields for. +get_atom_fields : Atom -> Array +get_atom_fields atom = @Builtin_Method "Meta.get_atom_fields" + +## UNSTABLE + ADVANCED + + Returns a vector of field values of the given atom. +Atom.fields : Vector.Vector +Atom.fields = Vector.Vector (here.get_atom_fields this.value) + +## UNSTABLE + ADVANCED + + Returns a constructor value of the given atom. +Atom.constructor : Atom_Constructor +Atom.constructor = here.get_atom_constructor this.value + +# Polyglot methods +## PRIVATE + + Get a textual representation of the language from which an object comes. + + Arguments: + - value: The value to obtain the source language for. +get_polyglot_language : Any -> Text +get_polyglot_language value = @Builtin_Method "Meta.get_polyglot_language" + +## UNSTABLE + ADVANCED + + Returns the language with which a polyglot value is associated. +Polyglot.get_language : Language +Polyglot.get_language = + lang_str = here.get_polyglot_language + if lang_str == "java" then Java else Unknown + +# UnresolvedSymbol methods +## PRIVATE + + Creates an unresolved symbol for the name name in the scope. + + Arguments: + - name: The name of the unresolved symbol. + - scope: The scope in which the symbol name is unresolved. +create_unresolved_symbol : Text -> Module_Scope -> Unresolved_Symbol +create_unresolved_symbol name scope = @Builtin_Method "Meta.create_unresolved_symbol" + +## PRIVATE + + Obtains the name of the provided unresolved symbol. + + Arguments: + - symbol: The unresolved symbol from which to get the name. +get_unresolved_symbol_name : Unresolved_Symbol -> Text +get_unresolved_symbol_name symbol = @Builtin_Method "Meta.get_unresolved_symbol_name" + +## PRIVATE + + Obtains the scope in which the provided unresolved symbol was created. + + Arguments: + - symbol: The unresolved symbol from which to get the scope. +get_unresolved_symbol_scope : Unresolved_Symbol -> Module_Scope +get_unresolved_symbol_scope symbol = @Builtin_Method "Meta.get_unresolved_symbol_scope" + +## UNSTABLE + ADVANCED + + Returns a new unresolved symbol with its name changed to the provided + argument. + + Arguments: + - new_name: The new name for the unresolved symbol. +Unresolved_Symbol.rename : Text -> Any +Unresolved_Symbol.rename new_name = + here.create_unresolved_symbol new_name this.scope + +## UNSTABLE + ADVANCED + + Returns the name of an unresolved symbol. +Unresolved_Symbol.name : Text +Unresolved_Symbol.name = here.get_unresolved_symbol_name this.value + +## UNSTABLE + ADVANCED + + Returns the definition scope of an unresolved symbol. +Unresolved_Symbol.scope : Any +Unresolved_Symbol.scope = here.get_unresolved_symbol_scope this.value + + +# Constructor methods +## PRIVATE + + Get the fields of an atom constructor. + + Arguments: + - atom_constructor: The constructor from which to get the fields. +get_constructor_fields : Atom_Constructor -> Array +get_constructor_fields atom_constructor = @Builtin_Method "Meta.get_constructor_fields" + +## PRIVATE + + Get the name of an atom constructor. + + Arguments: + - atom_constructor: The atom constructor from which to obtain the name. +get_constructor_name : Atom_Constructor -> Text +get_constructor_name atom_constructor = @Builtin_Method "Meta.get_constructor_name" + +## PRIVATE + + Constructs a new atom using the provided constructor and fields. + + Arguments: + - constructor: The constructor for the atom to create. + - fields: The arguments to pass to constructor. +new_atom : Atom_Constructor -> Array -> Atom +new_atom constructor fields = @Builtin_Method "Meta.new_atom" + +## UNSTABLE + ADVANCED + + Returns a vector of field names defined by a constructor. +Constructor.fields : Vector.Vector +Constructor.fields = Vector.Vector (here.get_constructor_fields this.value) + +## UNSTABLE + ADVANCED + + Returns the name of a constructor. +Constructor.name : Text +Constructor.name = here.get_constructor_name this.value + +## UNSTABLE + ADVANCED + + Creates a new atom of the given constructor. + + Arguments: + - fields: A vector of arguments to pass to the constructor when creating the + new atom. +Constructor.new : Vector.Vector -> Any +Constructor.new fields = here.new_atom this.value fields.to_array + ## UNSTABLE ADVANCED @@ -10,11 +239,11 @@ import Standard.Builtins Arguments: - value: The runtime entity to get the meta representation of. meta : Any -> Meta -meta value = if Builtins.Meta.is_atom value then Atom value else - if Builtins.Meta.is_constructor value then Constructor value else - if Builtins.Meta.is_polyglot value then Polyglot value else - if Builtins.Meta.is_unresolved_symbol value then Unresolved_Symbol value else - if Builtins.Meta.is_error value then Error value.catch else +meta value = if here.is_atom value then Atom value else + if here.is_atom_constructor value then Constructor value else + if here.is_polyglot value then Polyglot value else + if here.is_unresolved_symbol value then Unresolved_Symbol value else + if here.is_error value then Error value.catch else Primitive value ## UNSTABLE @@ -26,7 +255,7 @@ meta value = if Builtins.Meta.is_atom value then Atom value else - value_1: The first value. - value_2: The second value. is_same_object : Any -> Any -> Boolean -is_same_object value_1 value_2 = Builtins.Meta.is_same_object value_1 value_2 +is_same_object value_1 value_2 = @Builtin_Method "Meta.is_same_object" ## UNSTABLE ADVANCED @@ -78,7 +307,7 @@ Base.Error.is_an typ = typ == Base.Error - typ: The type to check `this` against. is_a : Any -> Any -> Boolean is_a value typ = if typ == Any then True else - if Builtins.Meta.is_error value then typ == Base.Error else + if here.is_error value then typ == Base.Error else case value of Array -> typ == Array Boolean -> if typ == Boolean then True else value == typ @@ -90,7 +319,7 @@ is_a value typ = if typ == Any then True else _ -> meta_val = here.meta value case meta_val of - Atom _ -> if Builtins.meta.is_atom typ then typ == value else + Atom _ -> if here.is_atom typ then typ == value else meta_val.constructor == typ Constructor _ -> meta_typ = here.meta typ @@ -128,144 +357,61 @@ type Language An unknown language. type Unknown -## UNSTABLE - ADVANCED - - A meta-representation of a runtime value. - - ! Warning - The functionality contained in this module exposes certain implementation - details of the language. As such, the API has no stability guarantees and - is subject to change as the Enso interpreter evolves. -type Meta - - ## UNSTABLE - ADVANCED - - An Atom meta-representation. - - Arguments: - - value: The value of the atom in the meta representation. - type Atom value - - ## UNSTABLE - ADVANCED - - A constructor meta-representation. - - Arguments: - - value: The value of the constructor in the meta representation. - type Constructor value - - ## UNSTABLE - ADVANCED - - A primitive value meta-prepresentation. - - Arguments: - - value: The value of the primitive object in the meta representation. - type Primitive value - - ## UNSTABLE - ADVANCED - - An unresolved symbol meta-representation. - - Arguments: - - value: The value of the unresolved symbol in the meta representation. - type Unresolved_Symbol value - - ## UNSTABLE - ADVANCED - - An error meta-representation, containing the payload of a dataflow error. - - Arguments: - - value: The payload of the error. - type Error value - - ## UNSTABLE - ADVANCED +## PRIVATE - A polyglot value meta-representation. + Checks if the provided value is an atom constructor. - Arguments: - - value: The polyglot value contained in the meta representation. - type Polyglot value - -## UNSTABLE - ADVANCED + Arguments: + - value: The value to check. +is_atom_constructor : Any -> Boolean +is_atom_constructor value = @Builtin_Method "Meta.is_atom_constructor" - Returns a vector of field values of the given atom. -Atom.fields : Vector.Vector -Atom.fields = Vector.Vector (Builtins.Meta.get_atom_fields this.value) +## PRIVATE -## UNSTABLE - ADVANCED + Checks if the provided value is an atom. - Returns a constructor value of the given atom. -Atom.constructor : Any -Atom.constructor = Builtins.Meta.get_atom_constructor this.value + Arguments: + - value: The value to check. +is_atom : Any -> Boolean +is_atom value = @Builtin_Method "Meta.is_atom" -## UNSTABLE - ADVANCED +## PRIVATE - Returns a new unresolved symbol with its name changed to the provided - argument. + Checks if the provided value is a runtime error. Arguments: - - new_name: The new name for the unresolved symbol. -Unresolved_Symbol.rename : Text -> Any -Unresolved_Symbol.rename new_name = - Builtins.Meta.create_unresolved_symbol new_name this.scope - -## UNSTABLE - ADVANCED + - value: The value to check. +is_error : Any -> Boolean +is_error value = @Builtin_Method "Meta.is_error" - Returns the name of an unresolved symbol. -Unresolved_Symbol.name : Text -Unresolved_Symbol.name = Builtins.Meta.get_unresolved_symbol_name this.value - -## UNSTABLE - ADVANCED +## PRIVATE - Returns the definition scope of an unresolved symbol. -Unresolved_Symbol.scope : Any -Unresolved_Symbol.scope = Builtins.Meta.get_unresolved_symbol_scope this.value + Checks if the provided value is a polyglot value. -## UNSTABLE - ADVANCED + Arguments: + - value: The value to check. +is_polyglot : Any -> Boolean +is_polyglot value = @Builtin_Method "Meta.is_polyglot" - Returns a vector of field names defined by a constructor. -Constructor.fields : Vector.Vector -Constructor.fields = Vector.Vector (Builtins.Meta.get_constructor_fields this.value) +## PRIVATE -## UNSTABLE - ADVANCED + Checks if the provided value is an unresolved symbol. - Returns the name of a constructor. -Constructor.name : Text -Constructor.name = Builtins.Meta.get_constructor_name this.value + Arguments: + - value: The value to check. +is_unresolved_symbol : Any -> Boolean +is_unresolved_symbol value = @Builtin_Method "Meta.is_unresolved_symbol" -## UNSTABLE - ADVANCED +## PRIVATE - Creates a new atom of the given constructor. + Returns a Text representing the source location of a stack frame above + the call. Arguments: - - fields: A vector of arguments to pass to the constructor when creating the - new atom. -Constructor.new : Vector.Vector -> Any -Constructor.new fields = Builtins.Meta.new_atom this.value fields.to_array - -## UNSTABLE - ADVANCED - - Returns the language with which a polyglot value is associated. -Polyglot.get_language : Language -Polyglot.get_language = - lang_str = Builtins.Meta.get_polyglot_language - if lang_str == "java" then Java else Unknown + - frames_to_skip: how many frames on the stack to skip. Called with 0 + will return exact location of the call. +get_source_location_builtin : Integer -> Text +get_source_location_builtin frames_to_skip = @Builtin_Method "Meta.get_source_location_builtin" ## PRIVATE @@ -282,7 +428,7 @@ Polyglot.get_language = used carefully. get_source_location : Integer -> Text get_source_location skip_frames = - Builtins.Meta.get_source_location skip_frames+1 + here.get_source_location_builtin skip_frames+1 ## PRIVATE @@ -291,7 +437,7 @@ get_source_location skip_frames = Arguments: - value: The value for which to display the type. get_simple_type_name : Any -> Text -get_simple_type_name value = Builtins.Meta.get_simple_type_name value +get_simple_type_name value = @Builtin_Method "Meta.get_simple_type_name" ## PRIVATE @@ -300,4 +446,4 @@ get_simple_type_name value = Builtins.Meta.get_simple_type_name value Arguments: - value: the value to get the type of. get_qualified_type_name : Any -> Text -get_qualified_type_name value = Builtins.Meta.get_qualified_type_name value +get_qualified_type_name value = @Builtin_Method "Meta.get_qualified_type_name" diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetSourceLocationNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetSourceLocationNode.java index d597fcd6c1dc..b31df49b8d34 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetSourceLocationNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetSourceLocationNode.java @@ -10,7 +10,7 @@ @BuiltinMethod( type = "Meta", - name = "get_source_location", + name = "get_source_location_builtin", description = "Returns a textual representation of the location of the callsite.") public class GetSourceLocationNode extends Node { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 3444e656fa12..8500562817e1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -82,7 +82,6 @@ public static class Debug { private final Bool bool; private final DataflowError dataflowError; private final Error error; - private final Meta meta; private final Module module; private final ModuleScope scope; private final Mutable mutable; @@ -118,7 +117,6 @@ public Builtins(Context context) { new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); error = new Error(language, scope); function = new AtomConstructor("Function", scope).initializeFields(); - meta = new Meta(language, scope); mutable = new Mutable(this, language, scope); nothing = new AtomConstructor("Nothing", scope).initializeFields(); number = new Number(language, scope); @@ -254,7 +252,7 @@ private void readBuiltinsMetadata(ModuleScope scope) { try { URI resource = classLoader.getResource(MethodDefinition.META_PATH).toURI(); fs = initFileSystem(resource); - builtinMetaPath = Files.walk(Paths.get(resource)).flatMap(p -> acceptFiles(p)); + builtinMetaPath = Files.walk(Paths.get(resource)).flatMap(p -> acceptMetadataFiles(p)); } catch (Exception ioe) { ioe.printStackTrace(); builtinMetaPath = Stream.empty(); @@ -328,15 +326,9 @@ private FileSystem initFileSystem(URI uri) throws IOException } } - private Stream acceptFiles(Path path) { + private Stream acceptMetadataFiles(Path path) { if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(MethodDefinition.META_BUILTIN_EXTENSION)) { return Stream.of(path); - } else if (Files.isDirectory(path)) { - try { - return Files.walk(path).flatMap(p -> {if (p != path) return acceptFiles(p); else return Stream.empty();}); - } catch (IOException ioe) { - ioe.printStackTrace(); - } } return Stream.empty(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java deleted file mode 100644 index c56fddfcb2b5..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.meta.*; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** Container for builtin Meta programming capabilities */ -public class Meta { - - /** - * Creates and registers the relevant constructors. - * - * @param language the current language instance. - * @param scope the scope to register constructors in. - */ - public Meta(Language language, ModuleScope scope) { - AtomConstructor meta = new AtomConstructor("Meta", scope).initializeFields(); - scope.registerConstructor(meta); - - scope.registerMethod(meta, "get_simple_type_name", GetSimpleTypeNameMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "is_unresolved_symbol", IsUnresolvedSymbolMethodGen.makeFunction(language)); - scope.registerMethod( - meta, - "get_unresolved_symbol_name", - GetUnresolvedSymbolNameMethodGen.makeFunction(language)); - scope.registerMethod( - meta, - "get_unresolved_symbol_scope", - GetUnresolvedSymbolScopeMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "create_unresolved_symbol", CreateUnresolvedSymbolMethodGen.makeFunction(language)); - - scope.registerMethod(meta, "is_constructor", IsAtomConstructorMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_constructor_name", GetConstructorNameMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_constructor_fields", GetConstructorFieldNamesMethodGen.makeFunction(language)); - scope.registerMethod(meta, "new_atom", NewAtomInstanceMethodGen.makeFunction(language)); - - scope.registerMethod(meta, "is_atom", IsAtomMethodGen.makeFunction(language)); - scope.registerMethod(meta, "get_atom_fields", GetAtomFieldsMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_atom_constructor", GetAtomConstructorMethodGen.makeFunction(language)); - - scope.registerMethod(meta, "is_error", IsErrorMethodGen.makeFunction(language)); - - scope.registerMethod(meta, "is_polyglot", IsPolyglotMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_polyglot_language", GetPolyglotLanguageMethodGen.makeFunction(language)); - - scope.registerMethod(meta, "is_same_object", IsSameObjectMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_source_location", GetSourceLocationMethodGen.makeFunction(language)); - scope.registerMethod( - meta, "get_qualified_type_name", GetQualifiedTypeNameMethodGen.makeFunction(language)); - } -} diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 52fc23c48d0c..a7ac3c804ee6 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -442,190 +442,6 @@ type IO readln : Text readln = @Builtin_Method "IO.readln" -## Primitive reflective operations. -type Meta - - ## PRIVATE - - A container type for the primitive meta operations. - - These operations are wrapped in a much nicer form in Meta.enso. - @Builtin_Type - type Meta - - ## PRIVATE - - Creates an unresolved symbol for the name name in the scope. - - Arguments: - - name: The name of the unresolved symbol. - - scope: The scope in which the symbol name is unresolved. - create_unresolved_symbol : Text -> Module_Scope -> Unresolved_Symbol - create_unresolved_symbol name scope = - @Builtin_Method "Meta.create_unresolved_symbol" - - ## PRIVATE - - Gets the atom constructor instance for the provided atom. - - Arguments: - - atom: The atom to obtain the constructor for. - get_atom_constructor : Atom -> Atom_Constructor - get_atom_constructor atom = @Builtin_Method "Meta.get_atom_constructor" - - ## PRIVATE - - Get the fields for the provided atom. - - Arguments: - - atom: The atom to obtain the fields for. - get_atom_fields : Atom -> Array - get_atom_fields atom = @Builtin_Method "Meta.get_atom_fields" - - ## PRIVATE - - Get the fields of an atom constructor. - - Arguments: - - atom_constructor: The constructor from which to get the fields. - get_constructor_fields : Atom_Constructor -> Array - get_constructor_fields atom_constructor = - @Builtin_Method "Meta.get_constructor_fields" - - ## PRIVATE - - Get the name of an atom constructor. - - Arguments: - - atom_constructor: The atom constructor from which to obtain the name. - get_constructor_name : Atom_Constructor -> Text - get_constructor_name atom_constructor = - @Builtin_Method "Meta.get_constructor_name" - - ## PRIVATE - - Get a textual representation of the language from which an object comes. - - Arguments: - - value: The value to obtain the source language for. - get_polyglot_language : Any -> Text - get_polyglot_language value = @Builtin_Method "Meta.get_polyglot_language" - - ## PRIVATE - - Obtains the name of the provided unresolved symbol. - - Arguments: - - symbol: The unresolved symbol from which to get the name. - get_unresolved_symbol_name : Unresolved_Symbol -> Text - get_unresolved_symbol_name symbol = - @Builtin_Method "Meta.get_unresolved_symbol_name" - - ## PRIVATE - - Obtains the scope in which the provided unresolved symbol was created. - - Arguments: - - symbol: The unresolved symbol from which to get the scope. - get_unresolved_symbol_scope : Unresolved_Symbol -> Module_Scope - get_unresolved_symbol_scope symbol = - @Builtin_Method "Meta.get_unresolved_symbol_scope" - - ## PRIVATE - - Checks if the provided value is an atom constructor. - - Arguments: - - value: The value to check. - is_constructor : Any -> Boolean - is_constructor value = @Builtin_Method "Meta.is_atom_constructor" - - ## PRIVATE - - Checks if the provided value is an atom. - - Arguments: - - value: The value to check. - is_atom : Any -> Boolean - is_atom value = @Builtin_Method "Meta.is_atom" - - ## PRIVATE - - Checks if the provided value is a runtime error. - - Arguments: - - value: The value to check. - is_error : Any -> Boolean - is_error value = @Builtin_Method "Meta.is_error" - - ## PRIVATE - - Checks if the provided value is a polyglot value. - - Arguments: - - value: The value to check. - is_polyglot : Any -> Boolean - is_polyglot value = @Builtin_Method "Meta.is_polyglot" - - ## PRIVATE - - Checks if the provided values share the same underlying reference. - - Arguments: - - value_1: The first value. - - value_2: The second value. - is_same_object : Any -> Any -> Boolean - is_same_object value_1 value_2 = @Builtin_Method "Meta.is_same_object" - - ## PRIVATE - - Checks if the provided value is an unresolved symbol. - - Arguments: - - value: The value to check. - is_unresolved_symbol : Any -> Boolean - is_unresolved_symbol value = @Builtin_Method "Meta.is_unresolved_symbol" - - ## PRIVATE - - Constructs a new atom using the provided constructor and fields. - - Arguments: - - constructor: The constructor for the atom to create. - - fields: The arguments to pass to constructor. - new_atom : Atom_Constructor -> Array -> Atom - new_atom constructor fields = @Builtin_Method "Meta.new_atom" - - ## PRIVATE - - Returns a Text representing the source location of a stack frame above - the call. - - Arguments: - - frames_to_skip: how many frames on the stack to skip. Called with 0 - will return exact location of the call. - get_source_location : Integer -> Text - get_source_location frames_to_skip = @Builtin_Method "Meta.get_source_location" - - ## PRIVATE - - Pretty-prints the type of the provided value using the interpreter's - internal logic for printing types. - - Arguments: - - value: The value whose type should be printed. - get_simple_type_name : Any -> Text - get_simple_type_name value = @Builtin_Method "Meta.get_simple_type_name" - - ## PRIVATE - - Returns the fully qualified type name of the given value. - - Arguments: - - value: the value to get the type of. - get_qualified_type_name : Any -> Text - get_qualified_type_name value = @Builtin_Method "Meta.get_qualified_type_name" - ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or From 43840f2be50956184fb172e57ee0c29a40626c9b Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 8 Apr 2022 12:30:55 +0200 Subject: [PATCH 09/73] Revert "Move Boolean out of Builtins to std library" This reverts commit 6938b2d8b40f3af4f9a950682ec1c9104179b95f. --- .../Base/0.0.0-dev/src/Data/Boolean.enso | 131 ------------------ .../Base/0.0.0-dev/src/Data/List.enso | 1 - .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../interpreter/runtime/builtin/Bool.java | 17 +-- .../interpreter/runtime/builtin/Builtins.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 115 +++++++++++++++ .../enso/compiler/codegen/IrToTruffle.scala | 6 +- .../test/semantic/ConstructorsTest.scala | 1 - .../interpreter/test/semantic/EvalTest.scala | 2 - .../test/semantic/GlobalScopeTest.scala | 1 - .../test/semantic/SystemProcessTest.scala | 25 ---- .../scala/org/enso/std/test/BooleanTest.scala | 7 - .../scala/org/enso/std/test/NumberTest.scala | 3 +- 13 files changed, 125 insertions(+), 190 deletions(-) delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso deleted file mode 100644 index adeb64f37d69..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso +++ /dev/null @@ -1,131 +0,0 @@ -## Booleans. -type Boolean - - ## A type with only two possible values. FIXME REMOVE? - - The boolean type represents the two truth values of boolean logic. It is - primarily used for control-flow. - @Builtin_Type - type Boolean - - ## Compares two booleans for equality. - - Arguments: - - that: The boolean to compare this with. - - > Example - Comparing True to False to get False. - - True == False - == : Boolean -> Boolean - == that = @Builtin_Method "Boolean.==" - - ## Computes the logical and (conjunction) of two booleans. - - Arguments: - - that: The boolean to compute the conjunction of this with. - - ! Short Circuiting - This method is not implemented in a short-circuiting manner. This means - that even if this is False, it will also evaluate that. This is - for performance. - - > Example - Computing the conjunction of False and True (to get False). - - False && True - && : Boolean -> Boolean - && that = @Builtin_Method "Boolean.&&" - - ## Computes the logical or (disjunction) of two booleans. - - Arguments: - - that: The boolean to compute the disjunction of this with. - - ! Short Circuiting - This method is not implemented in a short-circuiting manner. This means - that even if this is True, it will also evaluate that. This is - for performance. - - > Example - Computing the disjunction of True and False (to get True). - - True || False - || : Boolean -> Boolean - || that = @Builtin_Method "Boolean.||" - - ## Compares two booleans and returns an ordering value. - - Arguments: - - that: The boolean to compare with the value of this. - - ! Short Circuiting - This method is not implemented in a short-circuiting manner. This means - that even if this is False, it will also evaluate that. This is - for performance. - - > Example - Computing the ordering of True and False (to get Greater). - - True.compare_to False - compare_to : Boolean -> Ordering - compare_to that = @Builtin_Method "Boolean.compare_to" - - ## Computes the logical negation of this. - - > Example - Negating True to get False. - - True.not - not : Boolean - not = @Builtin_Method "Boolean.not" - - ## Generates a human-readable text representation of the boolean. - - > Example - Converting the value True to text. - - True.to_text - to_text : Text - to_text = @Builtin_Method "Boolean.to_text" - -## The if-then-else control flow operator that executes one of two branches - based on a conditional. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - on_false: The computation to evaluate if this evaluates to False. - - Both of the arguments to this method are _lazy_, meaning that they will - only be evaluated if they are needed (based on the condition). - - > Example - Telling the user if a number 27 is divisible by three. - - if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" -if_then_else : Any -> Any -> Any -if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - -## The if-then control flow operator that executes a branch if the condition - is true, and otherwise returns Nothing. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - The argument to this method is _lazy_, meaning that it will only be - evaluated if the this evaluates to True. - - > Example - Printing a message to the user only if a number is divisible by three. - - if (27 % 3) == 0 then IO.println "Fizz" -if_then : Any -> Any | Nothing -if_then ~on_true = @Builtin_Method "Boolean.if_then" - -## The constructor for the value True. -@Builtin_Type -type True - -## The constructor for the value False. -@Builtin_Type -type False diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 87a117c61799..f28e03968131 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,6 +1,5 @@ from Standard.Builtins import all from Standard.Builtins export Nil, Cons -from Standard.Base.Data.Boolean import all ## The basic cons-list type. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 0ad2bcf61c39..d3bb0677d961 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -1,4 +1,3 @@ -import project.Data.Boolean import project.Data.Any.Extensions import project.Data.Array import project.Data.Interval @@ -30,7 +29,7 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Any, Cons, Arithmetic_Error +from Standard.Builtins import Nothing, Number, Integer, Any, True, False, Cons, Boolean, Arithmetic_Error export project.Data.Interval export project.Data.Json @@ -48,7 +47,6 @@ export project.System.File export project.Data.Text.Regex.Mode as Regex_Mode export project.Warning -from project.Data.Boolean export all from project.Data.Array export Array from project.Data.Any.Extensions export all from project.Data.List export Nil, Cons diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java index 8e353a2ee1da..dd5cdf2be930 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java @@ -10,7 +10,6 @@ public class Bool { private final AtomConstructor tru; private final AtomConstructor fls; private final AtomConstructor bool; - private final Builtins builtins; /** * Creates and registers all the boolean constructors. @@ -18,12 +17,8 @@ public class Bool { * @param language the current language instance. * @param scope the scope to register constructors and methods in. */ - public Bool(Builtins builtins, Language language, ModuleScope scope) { - this.builtins = builtins; - tru = null; - fls = null; - bool = null; - /*bool = new AtomConstructor("Boolean", scope).initializeFields(); + public Bool(Language language, ModuleScope scope) { + bool = new AtomConstructor("Boolean", scope).initializeFields(); scope.registerConstructor(bool); scope.registerMethod(bool, "if_then_else", IfThenElseMethodGen.makeFunction(language)); scope.registerMethod(bool, "if_then", IfThenMethodGen.makeFunction(language)); @@ -36,21 +31,21 @@ public Bool(Builtins builtins, Language language, ModuleScope scope) { tru = new AtomConstructor("True", scope).initializeFields(); scope.registerConstructor(tru); fls = new AtomConstructor("False", scope).initializeFields(); - scope.registerConstructor(fls);*/ + scope.registerConstructor(fls); } /** @return the atom constructor for {@code True}. */ public AtomConstructor getTrue() { - return builtins.getBuiltinType("True"); + return tru; } /** @return the atom constructor for {@code False}. */ public AtomConstructor getFalse() { - return builtins.getBuiltinType("False"); + return fls; } /** @return the atom constructor for {@code Boolean}. */ public AtomConstructor getBool() { - return builtins.getBuiltinType("Boolean"); + return bool; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 8500562817e1..41b3b5311c46 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -105,7 +105,7 @@ public Builtins(Context context) { builtinTypes = new HashMap<>(); any = new AtomConstructor("Any", scope).initializeFields(); - bool = new Bool(this, language, scope); + bool = new Bool(language, scope); debug = new AtomConstructor("Debug", scope).initializeFields(); dataflowError = new DataflowError(language, scope); Warning.initWarningMethods(language, scope); diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index a7ac3c804ee6..074349e4d231 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -4,6 +4,121 @@ # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. +## Booleans. +type Boolean + + ## A type with only two possible values. + + The boolean type represents the two truth values of boolean logic. It is + primarily used for control-flow. + @Builtin_Type + type Boolean + + ## Compares two booleans for equality. + + Arguments: + - that: The boolean to compare this with. + + > Example + Comparing True to False to get False. + + True == False + == : Boolean -> Boolean + == that = @Builtin_Method "Boolean.==" + + ## Computes the logical and (conjunction) of two booleans. + + Arguments: + - that: The boolean to compute the conjunction of this with. + + ! Short Circuiting + This method is not implemented in a short-circuiting manner. This means + that even if this is False, it will also evaluate that. This is + for performance. + + > Example + Computing the conjunction of False and True (to get False). + + False && True + && : Boolean -> Boolean + && that = @Builtin_Method "Boolean.&&" + + ## Computes the logical or (disjunction) of two booleans. + + Arguments: + - that: The boolean to compute the disjunction of this with. + + ! Short Circuiting + This methid is not implemented in a short-circuiting manner. This means + that even if this is True, it will also evaluate that. This is + for performance. + + > Example + Computing the disjunction of True and False (to get True). + + True || False + || : Boolean -> Boolean + || that = @Builtin_Method "Boolean.||" + + ## Computes the logical negation of this. + + > Example + Negating True to get False. + + True.not + not : Boolean + not = @Builtin_Method "Boolean.not" + + ## Generates a human-readable text representation of the boolean. + + > Example + Converting the value True to text. + + True.to_text + to_text : Text + to_text = @Builtin_Method "Boolean.to_text" + + ## The if-then-else control flow operator that executes one of two branches + based on a conditional. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + - on_false: The computation to evaluate if this evaluates to False. + + Both of the arguments to this method are _lazy_, meaning that they will + only be evaluated if they are needed (based on the condition). + + > Example + Telling the user if a number 27 is divisible by three. + + if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" + if_then_else : Any -> Any -> Any + if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" + + ## The if-then control flow operator that executes a branch if the condition + is true, and otherwise returns Nothing. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + + The argument to this method is _lazy_, meaning that it will only be + evaluated if the this evaluates to True. + + > Example + Printing a message to the user only if a number is divisible by three. + + if (27 % 3) == 0 then IO.println "Fizz" + if_then : Any -> Any | Nothing + if_then ~on_true = @Builtin_Method "Boolean.if_then" + +## The constructor for the value True. +@Builtin_Type +type True + +## The constructor for the value False. +@Builtin_Type +type False + ## Debug utilities. type Debug diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 468a6cda39a1..d4fff69d4954 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -1,6 +1,6 @@ package org.enso.compiler.codegen -import com.oracle.truffle.api.{RootCallTarget, Truffle} +import com.oracle.truffle.api.Truffle import com.oracle.truffle.api.frame.FrameSlot import com.oracle.truffle.api.source.{Source, SourceSection} import org.enso.compiler.core.IR @@ -36,7 +36,6 @@ import org.enso.interpreter.{Constants, Language} import java.math.BigInteger import org.enso.compiler.core.IR.Name.Special -import org.enso.interpreter.runtime.builtin.Bool import org.enso.pkg.QualifiedName import scala.collection.{immutable, mutable} @@ -856,9 +855,6 @@ class IrToTruffle( // (array: AtomConstructor, branch: RootCallTarget) -> BranchNode // and related eta-expansion appear to crash Graal (not a joke). private val branchNodeFactories: Map[(QualifiedName, String), BranchNodeFactory] = immutable.HashMap[(QualifiedName, String), BranchNodeFactory]( - (QualifiedName(List("Standard", "Base"), "Boolean"), "True") -> { case (_: AtomConstructor, target: RootCallTarget) => BooleanBranchNode.build(true, target)}, - (QualifiedName(List("Standard", "Base"), "Boolean"), "False") -> { case (_: AtomConstructor, target: RootCallTarget) => BooleanBranchNode.build(false, target)}, - (QualifiedName(List("Standard", "Base"), "Boolean"), "Boolean") -> { case (bool: AtomConstructor, target: RootCallTarget) => BooleanConstructorBranchNode.build(bool.asInstanceOf[Bool], target)}, (QualifiedName(List("Standard", "Base"), "Polyglot"), "Polyglot") -> PolyglotBranchNode.build _, (QualifiedName(List("Standard", "Base", "Data"), "Array"), "Array") -> ArrayBranchNode.build _, ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index cb63431f9f2e..307150a5f9a1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala @@ -29,7 +29,6 @@ class ConstructorsTest extends InterpreterTest { "work with recursion" in { val testCode = """from Standard.Builtins import all - |from Standard.Base import all | |main = | genList = i -> if i == 0 then Nil else Cons i (genList (i - 1)) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala index 8d18ee864e29..1baa0c0766c4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala @@ -66,7 +66,6 @@ class EvalTest extends InterpreterTest { "work in a recursive setting" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | fn = sumTo -> @@ -81,7 +80,6 @@ class EvalTest extends InterpreterTest { "work inside a thunk passed to another function" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | fn = sumTo -> diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala index 8b9755c92d21..4da75318f52f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala @@ -59,7 +59,6 @@ class GlobalScopeTest extends InterpreterTest { "be able to mutually recurse in the global scope" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |Nothing.decrementCall = number -> | res = number - 1 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index 5a38feae769e..b79f6a1beb7b 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -20,7 +20,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" Array.empty "" False False False @@ -35,7 +34,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_1 "/c") "" False False False @@ -50,8 +48,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all - | |main = System.create_process "nonexistentcommandxyz" Array.empty "" False False False |""".stripMargin @@ -65,7 +61,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "ls" (Array.new_1 "--gibberish") "" False False False @@ -81,7 +76,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "exit 7") "" False False False @@ -97,7 +91,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; echo $line") "" True True True @@ -114,7 +107,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "" True True True @@ -132,7 +124,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "wc -c") "" True True True @@ -149,7 +140,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "42") "" True True True @@ -166,7 +156,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -183,7 +172,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "9") "" True True True @@ -199,7 +187,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -215,7 +202,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; printf $line") "hello" False False False @@ -231,7 +217,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "hello" False False False @@ -247,7 +232,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False True True @@ -263,7 +247,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False True True @@ -279,7 +262,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\x01\x0F\x10'") "" False True True @@ -295,7 +277,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False False False @@ -312,7 +293,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False False False @@ -329,7 +309,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False True True @@ -345,7 +324,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False True True @@ -361,7 +339,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\xCA\xFE\xBA\xBE' 1>&2") "" False True True @@ -377,7 +354,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False False False @@ -393,7 +369,6 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array - |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False False False diff --git a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala index b03ab174eda9..71f9058381f6 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala @@ -12,7 +12,6 @@ class BooleanTest extends InterpreterTest { "support if_then_else" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | if True then IO.println "true when true" else IO.println "false when true" @@ -25,7 +24,6 @@ class BooleanTest extends InterpreterTest { "support overriding methods on boolean" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |Boolean.isTrue = this | @@ -42,7 +40,6 @@ class BooleanTest extends InterpreterTest { "support pattern matching" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |to_num b = case b of | True -> 1 @@ -58,7 +55,6 @@ class BooleanTest extends InterpreterTest { "support per-constructor method overloads" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |True.to_num = 1 |False.to_num = 2 @@ -71,7 +67,6 @@ class BooleanTest extends InterpreterTest { "support per-single-constructor method overloads" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |Boolean.to_num = 2 |True.to_num = 1 @@ -84,7 +79,6 @@ class BooleanTest extends InterpreterTest { "support logical AND and OR operators" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | IO.println True&&False @@ -100,7 +94,6 @@ class BooleanTest extends InterpreterTest { "support negation" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | IO.println True.not diff --git a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala index 6743362469c4..6887c1c06df5 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala @@ -11,7 +11,6 @@ class NumberTest extends InterpreterTest { "support equality comparisons" in { val code = """from Standard.Builtins import all - |from Standard.Base import all | |main = | IO.println 7==5 @@ -23,7 +22,7 @@ class NumberTest extends InterpreterTest { "support a recursive sum case" in { val code = - """from Standard.Base import all + """ |main = sumTo -> | summator = acc -> current -> | if current == 0 then acc else summator acc+current current-1 From 9822d76def511facddee1e245adff266c15a22ec Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Sat, 9 Apr 2022 22:40:07 +0200 Subject: [PATCH 10/73] wip --- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../interop/generic/GetArraySizeNode.java | 2 +- .../expression/builtin/mutable/CopyNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 48 ++++++++--- .../interpreter/runtime/builtin/Mutable.java | 36 -------- .../callable/atom/AtomConstructor.java | 4 + .../enso/interpreter/runtime/data/Array.java | 4 +- .../interpreter/runtime/type/Constants.java | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 30 +++---- .../codegen/RuntimeStubsGenerator.scala | 4 +- .../test/semantic/PolyglotTest.scala | 86 +++++++++++++++++++ test/Tests/src/Data/Array_Spec.enso | 6 ++ test/Tests/src/Data/Bool_Spec.enso | 6 ++ 13 files changed, 154 insertions(+), 78 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index d3bb0677d961..7539aadae77c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -38,6 +38,7 @@ export project.Data.Map export project.Data.Maybe export project.Data.Ordering export project.Data.Ordering.Sort_Order +export project.Data.Ref export project.Data.Vector export project.Math export project.Meta @@ -54,7 +55,6 @@ from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise from project.Data.Pair export Pair from project.Data.Range export Range -from project.Data.Ref export Ref ## TODO [RW] Once autoscoping is implemented or automatic imports for ADTs are fixed in the IDE, we should revisit if we want to export ADTs like `Case` by default. It may be unnecessary pollution of scope, but until the issues are diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/GetArraySizeNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/GetArraySizeNode.java index 2e3e2afca566..5873a6bf51fb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/GetArraySizeNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/GetArraySizeNode.java @@ -26,7 +26,7 @@ long execute(Object _this, Object array) { err.enter(); Builtins builtins = Context.get(this).getBuiltins(); throw new PanicException( - builtins.error().makeTypeError(builtins.mutable().array(), array, "array"), this); + builtins.error().makeTypeError(builtins.array(), array, "array"), this); } } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java index e103d59a24ec..6110aae5903c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java @@ -67,6 +67,6 @@ Object doOther( Object _this, Object src, long source_index, Array dest, long dest_index, long count) { Builtins builtins = Context.get(this).getBuiltins(); throw new PanicException( - builtins.error().makeTypeError(builtins.mutable().array().newInstance(), src, "src"), this); + builtins.error().makeTypeError(builtins.array().newInstance(), src, "src"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 41b3b5311c46..d2f29d85eafa 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -84,7 +84,6 @@ public static class Debug { private final Error error; private final Module module; private final ModuleScope scope; - private final Mutable mutable; private final Number number; private final Ordering ordering; private final Resource resource; @@ -117,7 +116,6 @@ public Builtins(Context context) { new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); error = new Error(language, scope); function = new AtomConstructor("Function", scope).initializeFields(); - mutable = new Mutable(this, language, scope); nothing = new AtomConstructor("Nothing", scope).initializeFields(); number = new Number(language, scope); ordering = new Ordering(language, scope); @@ -205,8 +203,32 @@ public Builtins(Context context) { scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); readBuiltinsMetadata(scope); + + List builtinConstructors = new ArrayList<>(); + builtinConstructors.add("Polyglot"); + builtinConstructors.add("Ref"); + builtinConstructors.add("Array"); + initBuiltinTypes(builtinConstructors, scope, language); } + public void initBuiltinTypes(List constrs, ModuleScope scope, Language language) { + for (String constr: constrs) { + AtomConstructor atom = new AtomConstructor(constr, scope).initializeFields(); + builtinTypes.put(constr, atom); + Map> methods = builtinNodes.get(constr); + methods.forEach((methodName, clazz) -> { + Optional fun; + try { + Method meth = clazz.getMethod("makeFunction", Language.class); + fun = Optional.ofNullable((Function) meth.invoke(null, language)); + } catch (Exception e) { + e.printStackTrace(); + fun = Optional.empty(); + } + fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); + }); + } + } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ public boolean isIrInitialized() { return this.module.getIr() != null; @@ -350,13 +372,6 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } - public void registerBuiltinType(AtomConstructor atom) { - if (builtinTypes.containsKey(atom.getName())) { - throw new CompilerError("Builtin type '" + atom.getName() + "' already registered"); - } - builtinTypes.put(atom.getName(), atom); - } - public AtomConstructor getBuiltinType(String name) { return builtinTypes.get(name); } @@ -435,9 +450,14 @@ public System system() { return system; } - /** @return the container for mutable memory related builtins. */ - public Mutable mutable() { - return mutable; + /** @return the Array constructor. */ + public AtomConstructor array() { + return builtinTypes.get("Array"); + } + + /** @return the Ref constructor. */ + public AtomConstructor ref() { + return builtinTypes.get("Ref"); } /** @return the container for polyglot-related builtins. */ @@ -489,7 +509,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.ANY: return any.newInstance(); case Constants.ARRAY: - return mutable.array().newInstance(); + return array().newInstance(); case Constants.BOOLEAN: return bool.getBool().newInstance(); case Constants.DECIMAL: @@ -509,7 +529,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.PANIC: return panic.newInstance(); case Constants.REF: - return mutable.ref().newInstance(); + return ref().newInstance(); case Constants.TEXT: return text.getText().newInstance(); default: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java deleted file mode 100644 index a88e97e97d63..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.mutable.*; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** Container for builtin array-related types and functions. */ -public class Mutable { - private final AtomConstructor array; - private final AtomConstructor ref; - private final Builtins builtins; - - /** - * Creates a new instance of this class, registering all relevant bindings in the provided scope. - * - * @param language the current language instance. - * @param scope the scope for builtin methods. - */ - public Mutable(Builtins builtins, Language language, ModuleScope scope) { - array = null; - ref = null; - this.builtins = builtins; - - } - - /** @return the Array constructor. */ - public AtomConstructor array() { - return builtins.getBuiltinType("Array"); - } - - /** @return the Ref constructor. */ - public AtomConstructor ref() { - return builtins.getBuiltinType("Ref"); - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index 7b031d928597..7c6f83f5b9cd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -52,6 +52,10 @@ public AtomConstructor(String name, ModuleScope definitionScope) { } + public boolean isInitialized() { + return constructorFunction != null; + } + /** * Generates a constructor function for this {@link AtomConstructor}. * Note that such manually constructed argument definitions must not have default arguments. diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Array.java index 62cd2478c29d..5158772cd202 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Array.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Array.java @@ -131,7 +131,7 @@ static class GetFunctionalDispatch { static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); return symbol.resolveFor( - context.getBuiltins().mutable().array(), context.getBuiltins().any()); + context.getBuiltins().array(), context.getBuiltins().any()); } static Context getContext() { @@ -178,7 +178,7 @@ static class GetConversionFunction { static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { Context context = getContext(); return conversion.resolveFor( - target, context.getBuiltins().mutable().array(), context.getBuiltins().any()); + target, context.getBuiltins().array(), context.getBuiltins().any()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 4c3e8f0e5cc2..e0c3dd0ce025 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -15,7 +15,7 @@ public class Constants { public static final String NOTHING = "Standard.Builtins.Main.Nothing"; public static final String NUMBER = "Standard.Builtins.Main.Number"; public static final String PANIC = "Standard.Builtins.Main.Panic"; - public static final String REF = "Standard.Builtins.Main.Ref"; + public static final String REF = "Standard.Base.Data.Ref.Ref"; public static final String TEXT = "Standard.Builtins.Main.Text"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index d4fff69d4954..a878c946a239 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -36,9 +36,8 @@ import org.enso.interpreter.{Constants, Language} import java.math.BigInteger import org.enso.compiler.core.IR.Name.Special -import org.enso.pkg.QualifiedName -import scala.collection.{immutable, mutable} +import scala.collection.mutable import scala.collection.mutable.ArrayBuffer /** This is an implementation of a codegeneration pass that lowers the Enso @@ -193,8 +192,9 @@ class IrToTruffle( } val (assignments, reads) = argumentExpressions.unzip - - atomCons.initializeFields(localScope, assignments.toArray, reads.toArray, argDefs: _*) + if (!atomCons.isInitialized) { + atomCons.initializeFields(localScope, assignments.toArray, reads.toArray, argDefs: _*) + } } // Register the method definitions in scope @@ -793,10 +793,10 @@ class IrToTruffle( runtimeConsOpt.map { atomCons => val any = context.getBuiltins.any - //val array = context.getBuiltins.mutable().array() + val array = context.getBuiltins.array val bool = context.getBuiltins.bool val number = context.getBuiltins.number - //val polyglot = context.getBuiltins.polyglot + val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text val branchNode: BranchNode = if (atomCons == bool.getTrue) { @@ -819,9 +819,10 @@ class IrToTruffle( ) } else if (atomCons == number.getNumber) { NumberBranchNode.build(number, branchCodeNode.getCallTarget) - } else if (atomCons.getDefinitionScope.isBuiltin(atomCons)) { - val key = (atomCons.getDefinitionScope.getModule.getName, atomCons.getName) - branchNodeFactories(key).create(atomCons, branchCodeNode.getCallTarget) + } else if (atomCons == polyglot) { + PolyglotBranchNode.build(atomCons, branchCodeNode.getCallTarget) + } else if (atomCons == array) { + ArrayBranchNode.build(atomCons, branchCodeNode.getCallTarget) } else if (atomCons == any) { CatchAllBranchNode.build(branchCodeNode.getCallTarget) } else { @@ -848,17 +849,6 @@ class IrToTruffle( } } - // FIXME: Consider a different key mapping, and going back to reference - // checking from builtins, if too expensive and automatic mapping - // is not necessary. - // SAM-type BranchNodeFactory is necessary here because types like - // (array: AtomConstructor, branch: RootCallTarget) -> BranchNode - // and related eta-expansion appear to crash Graal (not a joke). - private val branchNodeFactories: Map[(QualifiedName, String), BranchNodeFactory] = immutable.HashMap[(QualifiedName, String), BranchNodeFactory]( - (QualifiedName(List("Standard", "Base"), "Polyglot"), "Polyglot") -> PolyglotBranchNode.build _, - (QualifiedName(List("Standard", "Base", "Data"), "Array"), "Array") -> ArrayBranchNode.build _, - ) - /* Note [Pattern Match Fallbacks] * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Enso in its current state has no coverage checking for constructors on diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index fd916afdf63f..1502c3b3fe91 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -25,8 +25,8 @@ class RuntimeStubsGenerator(builtins: Builtins) { localBindings.types.foreach { tp => val constructor = new AtomConstructor(tp.name, scope) if (tp.builtinType) { - scope.registerBuiltinConstructor(constructor) - builtins.registerBuiltinType(constructor) + val builtinType = builtins.getBuiltinType(tp.name) + scope.registerBuiltinConstructor(builtinType) } else { scope.registerConstructor(constructor) } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index 008a8faa5016..9ad963805dbb 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -56,5 +56,91 @@ class PolyglotTest extends InterpreterTest { "callFunctionAndIncrement" ) } + + "match on Polyglot type when imported everything from stdlib" in { + val code = + """from Standard.Base import all + |from Standard.Builtins import IO, Nothing + |polyglot java import java.util.Random + | + |main = + | random_gen = Random.new + | case random_gen of + | Polyglot -> IO.println "OK" + | _ -> IO.println "FAIL" + |""".stripMargin + eval(code) + val count :: Nil = consumeOut + count shouldEqual "OK" + } + + "fail to match on Polyglot type when explicitly importing everything from Polyglot module" in { + val code = + """from Standard.Base.Polyglot import all + |from Standard.Builtins import IO, Nothing + |polyglot java import java.util.Random + | + |main = + | random_gen = Random.new + | case random_gen of + | Polyglot -> IO.println "OK" + | _ -> IO.println "FAIL" + |""".stripMargin + eval(code) + val count :: Nil = consumeOut + count shouldEqual "FAIL" + } + + "fail to match on Polyglot type case when importing Polyglot module" in { + val code = + """import Standard.Base.Polyglot + |from Standard.Builtins import IO, Nothing + |polyglot java import java.util.Random + | + |main = + | random_gen = Random.new + | case random_gen of + | Polyglot -> IO.println "OK" + | _ -> IO.println "FAIL" + |""".stripMargin + eval(code) + val count :: Nil = consumeOut + count shouldEqual "FAIL" + } + + "match on qualified name of the Polyglot type from Polyglot module" in { + val code = + """import Standard.Base.Polyglot + |from Standard.Builtins import IO, Nothing + |polyglot java import java.util.Random + | + |main = + | random_gen = Random.new + | case random_gen of + | Polyglot.Polyglot -> IO.println "OK" + | _ -> IO.println "FAIL" + |""".stripMargin + eval(code) + val count :: Nil = consumeOut + count shouldEqual "OK" + } + + "match on qualified name of the Polyglot type from Polyglot module" in { + val code = + """import Standard.Base.Polyglot + |from Standard.Builtins import IO, Nothing + |polyglot java import java.util.Random + | + |main = + | random_gen = Random.new + | case random_gen of + | Polyglot.Polyglot -> IO.println "OK" + | _ -> IO.println "FAIL" + |""".stripMargin + eval(code) + val count :: Nil = consumeOut + count shouldEqual "OK" + } + } } diff --git a/test/Tests/src/Data/Array_Spec.enso b/test/Tests/src/Data/Array_Spec.enso index 0cb5c916d378..3b6dab1ca72a 100644 --- a/test/Tests/src/Data/Array_Spec.enso +++ b/test/Tests/src/Data/Array_Spec.enso @@ -2,6 +2,8 @@ from Standard.Base import all import Standard.Test +Array.method = 0 + spec = Test.group "Arrays" <| Test.specify "should be able to be converted to a visualization rep" <| arr = Vector.fill 1000 0 . to_array @@ -27,4 +29,8 @@ spec = Test.group "Arrays" <| Test.expect_panic_with (arr.at 3) Invalid_Array_Index_Error Test.expect_panic_with (arr.set_at 3 100) Invalid_Array_Index_Error + Test.specify "should allow for functional dispatch on a method defined in this module" + arr = [1, 2, 3] . to_array + arr.method . should_equal 0 + main = Test.Suite.run_main here.spec diff --git a/test/Tests/src/Data/Bool_Spec.enso b/test/Tests/src/Data/Bool_Spec.enso index 6c189ccec63d..27b12a7ff88f 100644 --- a/test/Tests/src/Data/Bool_Spec.enso +++ b/test/Tests/src/Data/Bool_Spec.enso @@ -3,6 +3,8 @@ from Standard.Base import all import Standard.Test from Standard.Base.Data.Ordering import Equal, Less, Greater +Boolean.method = this + spec = Test.group "Booleans" <| Test.specify "should allow converting Bools to Text values" <| @@ -15,4 +17,8 @@ spec = True.compare_to False . should_equal Greater False.compare_to True . should_equal Less + Test.specify "should allow for extending Bools in a local module" <| + test = 1 == 2 + test.method . should_equal test + main = Test.Suite.run_main here.spec From e5615650713c1bb94f74cfe79a4719254f0cdd54 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 11 Apr 2022 16:24:22 +0200 Subject: [PATCH 11/73] Move Any to stdlib In order to be able to locally extend a builtin type, we have to be able to then find it during symbol resolution. Since the symbol is being added to a module in stdlib but resolution would be using Any special builtin type, the latter has to be aware of the former via shadowdefinitions reference. --- .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 373 ++++++++++++++++++ .../0.0.0-dev/src/Data/Any/Extensions.enso | 343 ---------------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../interpreter/runtime/builtin/Builtins.java | 23 +- .../callable/atom/AtomConstructor.java | 4 +- .../callable/atom/BuiltinAtomConstructor.java | 39 ++ .../runtime/scope/ModuleScope.java | 14 + .../interpreter/runtime/type/Constants.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 30 -- .../codegen/RuntimeStubsGenerator.scala | 1 + .../pass/resolve/MethodDefinitions.scala | 6 +- .../test/semantic/InteropTest.scala | 2 +- .../test/semantic/MethodsTest.scala | 3 +- .../test/semantic/PolyglotTest.scala | 19 +- 14 files changed, 446 insertions(+), 417 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any/Extensions.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso new file mode 100644 index 000000000000..5c63cab5c8c6 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -0,0 +1,373 @@ +from Standard.Base import all + +# The type that subsumes all types. +type Any + + ## Any is the universal top-type, with all other types being subsumed by it. + + If a value of type Any is expected in a given location, _any value_ can + be used in that position. + @Builtin_Type + type Any + + ## PRIVATE + + Executes the provided handler on a dataflow error, or executes as + identity on a non-error value. + + Arguments: + - handler: The function to call on this if it is an error value. + catch_primitive : (Error -> Any) -> Any + catch_primitive handler = @Builtin_Method "Any.catch" + + ## Generic conversion of an arbitrary Enso value to a corresponding textual + representation. + + > Example + Getting a textual representation of the number 7. + + 7.to_text + to_text : Text + to_text = @Builtin_Method "Any.to_text" + + ## ALIAS Equality + + Checks if `this` is equal to `that`. + + Arguments: + - that: The object to compare `this` with. + + Two values are considered to be equal in Enso when they obey the following + recursive properties: + - At each level, they have the same structure. + - The value of each field in `this` is equal (by this definition) to the + corresponding field in `that`. + + ! Implementing Your Own Equality + Equality in Enso is defined to allow comparison of any two values + (universal equality), no matter if they are not directly comparable. When + implementing equality for your own types, keep in mind that it needs to + work with any Enso value as the `that` argument. + + ? Generic Equality and Performance + While the generic equality provided here will work for _all_ values in + Enso, its performance may often be suboptimal. Many types can implement + their own equality operations that will be more efficient than these. + + > Example + Checking if the variable `a` is equal to `147`. + + from Standard.Base import all + + example_equality = + a = 7 * 21 + a == 147 + == : Any -> Boolean + == that = if Meta.is_same_object this that then True else + this_meta = Meta.meta this + that_meta = Meta.meta that + case Cons this_meta that_meta of + Cons (Meta.Atom _) (Meta.Atom _) -> + c_1 = this_meta.constructor + c_2 = that_meta.constructor + if Meta.is_same_object c_1 c_2 . not then False else + f_1 = this_meta.fields + f_2 = that_meta.fields + 0.up_to f_1.length . all i-> (f_1.at i) == (f_2.at i) + Cons (Meta.Error _) (Meta.Error _) -> this_meta.payload == that_meta.payload + Cons (Meta.Polyglot o_1) (Meta.Polyglot o_2) -> + langs_match = (this_meta.get_language == Meta.Java) && (that_meta.get_language == Meta.Java) + if langs_match.not then False else o_1.equals o_2 + Cons (Meta.Unresolved_Symbol _) (Meta.Unresolved_Symbol _) -> + (this_meta.name == that_meta.name) && (this_meta.scope == that_meta.scope) + ## Constructor comparison is covered by the identity equality. + Primitive objects should define their own equality. + Therefore, there are no more cases to handle in this method. + _ -> False + + ## ALIAS Inequality + + Checks if `this` is not equal to `that`. + + Arguments: + - that: The object to compare `this` against. + + ! Implementing Your Own Inequality + We recommend that you do not implement your own inequality, instead relying + on the default definition given here. If you do, please ensure that you + satisfy universal equality, as described in the documentation for `Any.==`. + + > Example + Checking if the variable `a` is not equal to `147`. + + from Standard.Base import all + + example_inequality = + a = 7 * 21 + a != 147 + != : Any -> Boolean + != that = (this == that).not + + ## ALIAS Greater Than + + Checks if `this` is greater than `that`. + + Arguments: + - that: The value to compare `this` against. + + To have `>` defined, a type must define `compare_to`, returning an Ordering. + + ! Implementing Greater Than + Many types can admit a definition of greater than that is more efficient + than the generic one given here. When implementing this for your own types + please ensure that it is semantically equivalent to using `.compare_to`. + + > Example + Checking if the variable `a` is greater than `147`. + + from Standard.Base import all + + example_greater = + a = 7 * 28 + a > 147 + > : Any -> Boolean + > that = this.compare_to that == Ordering.Greater + + ## ALIAS Greater Than or Equal + + Checks if `this` is greater than or equal to `that`. + + Arguments: + - that: The value to compare `this` against. + + To have `>=` defined, a type must define both `>` and `==`. + + ! Implementing Greater Than or Equal + While it is often possible to implement a more efficient version of this + operation for complex types, care must be taken to ensure that your + implementation is semantically equivalent to the disjunction of the + greater than and equal to operations. + + > Example + Checking if the variable `a` is greater than or equal to `147`. + + from Standard.Base import all + + example_greater_eq = + a = 6 * 21 + a >= 147 + >= : Any -> Boolean + >= that = (this > that) || (this == that) + + ## ALIAS Less Than + + Checks if `this` is less than `that`. + + Arguments: + - that: The value to compare `this` against. + + To have `<` defined, a type must define `compare_to`, returning an Ordering. + + ! Implementing Less Than + Many types can admit a definition of less than that is more efficient than + the generic one given here. When implementing this for your own types + please ensure that it is semantically equivalent to using `.compare_to`. + + > Example + Checking if the variable `a` is less than `147`. + + from Standard.Base import all + + example_less = + a = 7 * 21 + a < 147 + < : Any -> Boolean + < that = this.compare_to that == Ordering.Less + + ## ALIAS Less Than or Equal + + Checks if `this` is less than or equal to `that`. + + Arguments: + - that: The value to compare `this` against. + + To have `<=` defined, a type must define both `<` and `==`. + + ! Implementing Less Than or Equal + While it is often possible to implement a more efficient version of this + operation for complex types, care must be taken to ensure that your + implementation is semantically equivalent to the disjunction of the + less than than and equal to operations. + + > Example + Checking if the variable `a` is less than or equal to `147`. + + from Standard.Base import all + + example_less_eq = + a = 7 * 21 + a < 147 + <= : Any -> Boolean + <= that = (this < that) || (this == that) + + ## Checks if the type is an instance of `Nothing`. + + Nothing in Enso is used as a universal value to indicate the lack of presence + of a value. This function is primarily useful in the IDE. + + > Example + Checking if the value 1 is nothing. + + 1.is_nothing + is_nothing : Boolean + is_nothing = case this of + Nothing -> True + _ -> False + + ## Executes the provided handler on an error, or returns a non-error value + unchanged. + + Arguments: + - handler: The function to call on this if it is an error value. By default + this is identity. + + > Example + Catching an erroneous value and getting the length of its message. + + from Standard.Base import all + + example_catch = + error = Error.throw "My message" + error.catch (err -> err.length) + catch : (Error -> Any) -> Any + catch (handler = x->x) = this.catch_primitive handler + + ## Transforms an error. + + Arguments: + - f: The function used to transform the error. + + If `this` is a non-error value it is returned unchanged. However, if `this` + is an error, the error is transformed using the provided function. + + > Example + Transforming an error value to provide more information. + + from Standard.Base import all + from Standard.Examples import Example_Error_Type + + example_map_error = + my_map = Map.empty + error = my_map.get "x" + error.map_error (_ -> Example_Error_Type "x is missing") + map_error : (Error -> Error) -> Any + map_error _ = this + + ## Checks if `this` is an error. + + > Example + Checking if the provided value is an error. + + 1.is_error + is_error : Boolean + is_error = False + + ## Applies the provided function to `this` unless `this` is `Nothing`, which is + returned unchanged. + + Arguments: + - f: The function to apply to `this` if `this` is not `Nothing`. + + > Example + Applying a function over a value 10. + + 10.map_nothing *2 + map_nothing : (a -> b) -> b | Nothing + map_nothing f = case this of + Nothing -> Nothing + a -> f a + + ## Applies the function `this` to the provided argument. + + Arguments: + - argument: The argument to apply `this` to. + + ? Piping Blocks to Functions + This construction is particularly useful for passing a block as an argument + to a function. This means that you can compute more sophisticated values + in-line, as shown in the example below. + + > Example + Applying a function to a block. + + (x -> x + 1) <| + y = 1 ^ 3 + 3 + y + <| : Any -> Any + <| ~argument = this argument + + ## Applies the function on the right hand side to the argument on the left. + + Arguments + - function: The function to apply to `this`. + + ? `|>` or `.`? + The eagle-eyed reader will notice that the operator dot (`.`) is very + similar to the operator `|>`. In Enso, with the variable precedence of + operators, this makes perfect sense. In general, we recommend using `.`. + However, there are some contexts where variable precedence might be unclear + or confusing, or where the function being applied is not a method. In these + contexts we recommend using `|>`. + + > Example + Applying multiple functions in a pipeline to compute a number and transform + it to text. + + 1 |> (* 2) |> (/ 100) |> .to_text + |> : (Any -> Any) -> Any + |> ~function = function this + + ## Composes two functions together, for `f << g` creating the function + composition `f ∘ g` (equivalent to `x -> f (g x)`). + + Arguments: + - that: The function to compose with `this`. + + > Example + Multiply by 2 and then add 1 as a function applied to 2. + + (+1 << *2) 2 + << : (Any -> Any) -> (Any -> Any) -> Any -> Any + << ~that = x -> this (that x) + + ## Composes two functions together in the forward direction, for `f >> g` + creating the function composition `g ∘ f` (equivalent to `x -> g (f (x))`). + + Arguments: + - that: The function to compose with `this`. + + > Example + Add one and then multiply by two as a function applied to 2. + + (+1 >> *2) 2 + >> : (Any -> Any) -> (Any -> Any) -> Any -> Any + >> ~that = x -> that (this x) + + ## UNSTABLE + ADVANCED + + Returns a Text used to display this value in the IDE. + + The particular representation is left unspecified and subject to change in + the future. The current implementation uses JSON serialization as the + default. + + Types defining their own versions of this method should ensure that the + result is reasonably small and that the operation is quick to compute. + + > Example + Converting the number `2` into visualization data. + + 2.to_default_visualization_data + to_default_visualization_data : Text + to_default_visualization_data = this.to_json.to_text diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any/Extensions.enso deleted file mode 100644 index 11f8ee7fe4f6..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any/Extensions.enso +++ /dev/null @@ -1,343 +0,0 @@ -from Standard.Base import all - -## ALIAS Equality - - Checks if `this` is equal to `that`. - - Arguments: - - that: The object to compare `this` with. - - Two values are considered to be equal in Enso when they obey the following - recursive properties: - - At each level, they have the same structure. - - The value of each field in `this` is equal (by this definition) to the - corresponding field in `that`. - - ! Implementing Your Own Equality - Equality in Enso is defined to allow comparison of any two values - (universal equality), no matter if they are not directly comparable. When - implementing equality for your own types, keep in mind that it needs to - work with any Enso value as the `that` argument. - - ? Generic Equality and Performance - While the generic equality provided here will work for _all_ values in - Enso, its performance may often be suboptimal. Many types can implement - their own equality operations that will be more efficient than these. - - > Example - Checking if the variable `a` is equal to `147`. - - from Standard.Base import all - - example_equality = - a = 7 * 21 - a == 147 -Any.== : Any -> Boolean -Any.== that = if Meta.is_same_object this that then True else - this_meta = Meta.meta this - that_meta = Meta.meta that - case Cons this_meta that_meta of - Cons (Meta.Atom _) (Meta.Atom _) -> - c_1 = this_meta.constructor - c_2 = that_meta.constructor - if Meta.is_same_object c_1 c_2 . not then False else - f_1 = this_meta.fields - f_2 = that_meta.fields - 0.up_to f_1.length . all i-> (f_1.at i) == (f_2.at i) - Cons (Meta.Error _) (Meta.Error _) -> this_meta.payload == that_meta.payload - Cons (Meta.Polyglot o_1) (Meta.Polyglot o_2) -> - langs_match = (this_meta.get_language == Meta.Java) && (that_meta.get_language == Meta.Java) - if langs_match.not then False else o_1.equals o_2 - Cons (Meta.Unresolved_Symbol _) (Meta.Unresolved_Symbol _) -> - (this_meta.name == that_meta.name) && (this_meta.scope == that_meta.scope) - ## Constructor comparison is covered by the identity equality. - Primitive objects should define their own equality. - Therefore, there are no more cases to handle in this method. - _ -> False - -## ALIAS Inequality - - Checks if `this` is not equal to `that`. - - Arguments: - - that: The object to compare `this` against. - - ! Implementing Your Own Inequality - We recommend that you do not implement your own inequality, instead relying - on the default definition given here. If you do, please ensure that you - satisfy universal equality, as described in the documentation for `Any.==`. - - > Example - Checking if the variable `a` is not equal to `147`. - - from Standard.Base import all - - example_inequality = - a = 7 * 21 - a != 147 -Any.!= : Any -> Boolean -Any.!= that = (this == that).not - -## ALIAS Greater Than - - Checks if `this` is greater than `that`. - - Arguments: - - that: The value to compare `this` against. - - To have `>` defined, a type must define `compare_to`, returning an Ordering. - - ! Implementing Greater Than - Many types can admit a definition of greater than that is more efficient - than the generic one given here. When implementing this for your own types - please ensure that it is semantically equivalent to using `.compare_to`. - - > Example - Checking if the variable `a` is greater than `147`. - - from Standard.Base import all - - example_greater = - a = 7 * 28 - a > 147 -Any.> : Any -> Boolean -Any.> that = this.compare_to that == Ordering.Greater - -## ALIAS Greater Than or Equal - - Checks if `this` is greater than or equal to `that`. - - Arguments: - - that: The value to compare `this` against. - - To have `>=` defined, a type must define both `>` and `==`. - - ! Implementing Greater Than or Equal - While it is often possible to implement a more efficient version of this - operation for complex types, care must be taken to ensure that your - implementation is semantically equivalent to the disjunction of the - greater than and equal to operations. - - > Example - Checking if the variable `a` is greater than or equal to `147`. - - from Standard.Base import all - - example_greater_eq = - a = 6 * 21 - a >= 147 -Any.>= : Any -> Boolean -Any.>= that = (this > that) || (this == that) - -## ALIAS Less Than - - Checks if `this` is less than `that`. - - Arguments: - - that: The value to compare `this` against. - - To have `<` defined, a type must define `compare_to`, returning an Ordering. - - ! Implementing Less Than - Many types can admit a definition of less than that is more efficient than - the generic one given here. When implementing this for your own types - please ensure that it is semantically equivalent to using `.compare_to`. - - > Example - Checking if the variable `a` is less than `147`. - - from Standard.Base import all - - example_less = - a = 7 * 21 - a < 147 -Any.< : Any -> Boolean -Any.< that = this.compare_to that == Ordering.Less - -## ALIAS Less Than or Equal - - Checks if `this` is less than or equal to `that`. - - Arguments: - - that: The value to compare `this` against. - - To have `<=` defined, a type must define both `<` and `==`. - - ! Implementing Less Than or Equal - While it is often possible to implement a more efficient version of this - operation for complex types, care must be taken to ensure that your - implementation is semantically equivalent to the disjunction of the - less than than and equal to operations. - - > Example - Checking if the variable `a` is less than or equal to `147`. - - from Standard.Base import all - - example_less_eq = - a = 7 * 21 - a < 147 -Any.<= : Any -> Boolean -Any.<= that = (this < that) || (this == that) - -## Checks if the type is an instance of `Nothing`. - - Nothing in Enso is used as a universal value to indicate the lack of presence - of a value. This function is primarily useful in the IDE. - - > Example - Checking if the value 1 is nothing. - - 1.is_nothing -Any.is_nothing : Boolean -Any.is_nothing = case this of - Nothing -> True - _ -> False - -## Executes the provided handler on an error, or returns a non-error value - unchanged. - - Arguments: - - handler: The function to call on this if it is an error value. By default - this is identity. - - > Example - Catching an erroneous value and getting the length of its message. - - from Standard.Base import all - - example_catch = - error = Error.throw "My message" - error.catch (err -> err.length) -Any.catch : (Error -> Any) -> Any -Any.catch (handler = x->x) = this.catch_primitive handler - -## Transforms an error. - - Arguments: - - f: The function used to transform the error. - - If `this` is a non-error value it is returned unchanged. However, if `this` - is an error, the error is transformed using the provided function. - - > Example - Transforming an error value to provide more information. - - from Standard.Base import all - from Standard.Examples import Example_Error_Type - - example_map_error = - my_map = Map.empty - error = my_map.get "x" - error.map_error (_ -> Example_Error_Type "x is missing") -Any.map_error : (Error -> Error) -> Any -Any.map_error _ = this - -## Checks if `this` is an error. - - > Example - Checking if the provided value is an error. - - 1.is_error -Any.is_error : Boolean -Any.is_error = False - -## Applies the provided function to `this` unless `this` is `Nothing`, which is - returned unchanged. - - Arguments: - - f: The function to apply to `this` if `this` is not `Nothing`. - - > Example - Applying a function over a value 10. - - 10.map_nothing *2 -Any.map_nothing : (a -> b) -> b | Nothing -Any.map_nothing f = case this of - Nothing -> Nothing - a -> f a - -## Applies the function `this` to the provided argument. - - Arguments: - - argument: The argument to apply `this` to. - - ? Piping Blocks to Functions - This construction is particularly useful for passing a block as an argument - to a function. This means that you can compute more sophisticated values - in-line, as shown in the example below. - - > Example - Applying a function to a block. - - (x -> x + 1) <| - y = 1 ^ 3 - 3 + y -Any.<| : Any -> Any -Any.<| ~argument = this argument - -## Applies the function on the right hand side to the argument on the left. - - Arguments - - function: The function to apply to `this`. - - ? `|>` or `.`? - The eagle-eyed reader will notice that the operator dot (`.`) is very - similar to the operator `|>`. In Enso, with the variable precedence of - operators, this makes perfect sense. In general, we recommend using `.`. - However, there are some contexts where variable precedence might be unclear - or confusing, or where the function being applied is not a method. In these - contexts we recommend using `|>`. - - > Example - Applying multiple functions in a pipeline to compute a number and transform - it to text. - - 1 |> (* 2) |> (/ 100) |> .to_text -Any.|> : (Any -> Any) -> Any -Any.|> ~function = function this - -## Composes two functions together, for `f << g` creating the function - composition `f ∘ g` (equivalent to `x -> f (g x)`). - - Arguments: - - that: The function to compose with `this`. - - > Example - Multiply by 2 and then add 1 as a function applied to 2. - - (+1 << *2) 2 -Any.<< : (Any -> Any) -> (Any -> Any) -> Any -> Any -Any.<< ~that = x -> this (that x) - -## Composes two functions together in the forward direction, for `f >> g` - creating the function composition `g ∘ f` (equivalent to `x -> g (f (x))`). - - Arguments: - - that: The function to compose with `this`. - - > Example - Add one and then multiply by two as a function applied to 2. - - (+1 >> *2) 2 -Any.>> : (Any -> Any) -> (Any -> Any) -> Any -> Any -Any.>> ~that = x -> that (this x) - -## UNSTABLE - ADVANCED - - Returns a Text used to display this value in the IDE. - - The particular representation is left unspecified and subject to change in - the future. The current implementation uses JSON serialization as the - default. - - Types defining their own versions of this method should ensure that the - result is reasonably small and that the operation is quick to compute. - - > Example - Converting the number `2` into visualization data. - - 2.to_default_visualization_data -Any.to_default_visualization_data : Text -Any.to_default_visualization_data = this.to_json.to_text diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 7539aadae77c..87918c766644 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -1,4 +1,4 @@ -import project.Data.Any.Extensions +import project.Data.Any import project.Data.Array import project.Data.Interval import project.Data.Json @@ -49,7 +49,7 @@ export project.Data.Text.Regex.Mode as Regex_Mode export project.Warning from project.Data.Array export Array -from project.Data.Any.Extensions export all +from project.Data.Any export all from project.Data.List export Nil, Cons from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index d2f29d85eafa..02c0672d846f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -47,6 +47,7 @@ import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.callable.atom.BuiltinAtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.Constants; @@ -69,9 +70,8 @@ public static class Debug { private HashMap>> builtinNodes; // TODO Consider dropping the map and just assigning to a single variable since builtin types // should be unique - private HashMap builtinTypes; + private HashMap builtinTypes; - private final AtomConstructor any; private final AtomConstructor debug; private final AtomConstructor projectDescription; private final AtomConstructor function; @@ -103,7 +103,6 @@ public Builtins(Context context) { builtinNodes = new HashMap<>(); builtinTypes = new HashMap<>(); - any = new AtomConstructor("Any", scope).initializeFields(); bool = new Bool(language, scope); debug = new AtomConstructor("Debug", scope).initializeFields(); dataflowError = new DataflowError(language, scope); @@ -146,7 +145,6 @@ public Builtins(Context context) { AtomConstructor unsafe = new AtomConstructor("Unsafe", scope).initializeFields(); scope.registerConstructor(nothing); - scope.registerConstructor(any); scope.registerConstructor(function); scope.registerConstructor(cons); @@ -184,8 +182,6 @@ public Builtins(Context context) { "primitive_get_attached_stack_trace", GetAttachedStackTraceMethodGen.makeFunction(language)); scope.registerMethod(caughtPanic, "convert_to_dataflow_error", CaughtPanicConvertToDataflowErrorMethodGen.makeFunction(language)); - scope.registerMethod(any, "catch_primitive", CatchAnyMethodGen.makeFunction(language)); - scope.registerMethod(state, "get", GetStateMethodGen.makeFunction(language)); scope.registerMethod(state, "put", PutStateMethodGen.makeFunction(language)); scope.registerMethod(state, "run", RunStateMethodGen.makeFunction(language)); @@ -194,26 +190,25 @@ public Builtins(Context context) { scope.registerMethod(debug, "breakpoint", DebugBreakpointMethodGen.makeFunction(language)); scope.registerMethod(function, "call", ExplicitCallFunctionMethodGen.makeFunction(language)); - - scope.registerMethod(any, "to_text", AnyToTextMethodGen.makeFunction(language)); - scope.registerMethod(any, "to_display_text", AnyToDisplayTextMethodGen.makeFunction(language)); - scope.registerMethod( thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); readBuiltinsMetadata(scope); + // FIXME: should be possible to get rid of hardcoded list of builtin types once we have all of them + // stored in metadata files List builtinConstructors = new ArrayList<>(); builtinConstructors.add("Polyglot"); builtinConstructors.add("Ref"); builtinConstructors.add("Array"); + builtinConstructors.add("Any"); initBuiltinTypes(builtinConstructors, scope, language); } public void initBuiltinTypes(List constrs, ModuleScope scope, Language language) { for (String constr: constrs) { - AtomConstructor atom = new AtomConstructor(constr, scope).initializeFields(); + BuiltinAtomConstructor atom = new BuiltinAtomConstructor(constr, scope).initializeFields(); builtinTypes.put(constr, atom); Map> methods = builtinNodes.get(constr); methods.forEach((methodName, clazz) -> { @@ -372,7 +367,7 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } - public AtomConstructor getBuiltinType(String name) { + public BuiltinAtomConstructor getBuiltinType(String name) { return builtinTypes.get(name); } @@ -428,7 +423,7 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - return any; + return this.getBuiltinType("Any"); } /** @@ -507,7 +502,7 @@ public Module getModule() { public Atom fromTypeSystem(String typeName) { switch (typeName) { case Constants.ANY: - return any.newInstance(); + return any().newInstance(); case Constants.ARRAY: return array().newInstance(); case Constants.BOOLEAN: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index 7c6f83f5b9cd..b0b20dedfb40 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -11,6 +11,7 @@ import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; +import org.enso.compiler.exception.CompilerError; import org.enso.interpreter.node.ClosureRootNode; import org.enso.interpreter.node.ExpressionNode; import org.enso.interpreter.node.callable.argument.ReadArgumentNode; @@ -32,7 +33,7 @@ /** A representation of an Atom constructor. */ @ExportLibrary(InteropLibrary.class) @ExportLibrary(MethodDispatchLibrary.class) -public final class AtomConstructor implements TruffleObject { +public class AtomConstructor implements TruffleObject { private final String name; private final ModuleScope definitionScope; @@ -51,7 +52,6 @@ public AtomConstructor(String name, ModuleScope definitionScope) { this.definitionScope = definitionScope; } - public boolean isInitialized() { return constructorFunction != null; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java new file mode 100644 index 000000000000..c1454b01cc65 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java @@ -0,0 +1,39 @@ +package org.enso.interpreter.runtime.callable.atom; + +import com.oracle.truffle.api.interop.InteropLibrary; +import com.oracle.truffle.api.library.ExportLibrary; +import org.enso.compiler.exception.CompilerError; +import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; +import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.scope.ModuleScope; + +/** A representation of an Atom constructor for BuiltinType. */ +public class BuiltinAtomConstructor extends AtomConstructor { + + private ModuleScope shadowDefinitions; + /** + * Creates a new Atom constructor for a given name. The constructor is not valid until {@link + * AtomConstructor#initializeFields(LocalScope, ExpressionNode[], ExpressionNode[], ArgumentDefinition...)} is called. + * + * @param name the name of the Atom constructor + * @param definitionScope the scope in which this constructor was defined + */ + public BuiltinAtomConstructor(String name, ModuleScope definitionScope) { + super(name, definitionScope); + } + + public void setShadowDefinitions(ModuleScope scope) { + if (shadowDefinitions != null) { + throw new CompilerError("cannot set shadow definitions twice"); + } + this.shadowDefinitions = scope; + } + + public ModuleScope getShadowDefinitions() { + return this.shadowDefinitions; + } + + public BuiltinAtomConstructor initializeFields(ArgumentDefinition... args) { + return (BuiltinAtomConstructor)super.initializeFields(args); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 33ae1c98b608..ac55f764781c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -9,6 +9,7 @@ import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.callable.atom.BuiltinAtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.error.RedefinedMethodException; import org.enso.interpreter.runtime.error.RedefinedConversionException; @@ -241,6 +242,19 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { if (definedHere != null) { return definedHere; } + + if (atom instanceof BuiltinAtomConstructor) { + // Unfortunately locally defined extensions get associated with the module rather than a type within a module + // BindingsMap would need to be enhanced to resolve to the constructor rather than a module + ModuleScope shadowDefinitions = ((BuiltinAtomConstructor) atom).getShadowDefinitions(); + if (shadowDefinitions != null) { + AtomConstructor moduleTypeInStdLib = shadowDefinitions.associatedType; + definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); + if (definedHere != null) { + return definedHere; + } + } + } return imports.stream() .map(scope -> scope.getExportedMethod(atom, name)) .filter(Objects::nonNull) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index e0c3dd0ce025..56d15144e3c9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -3,7 +3,7 @@ /** Types defined in the Standard.Builtins module. */ public class Constants { - public static final String ANY = "Standard.Builtins.Main.Any"; + public static final String ANY = "Standard.Base.Data.Any.Any"; public static final String ARRAY = "Standard.Data.Main.Array"; public static final String BOOLEAN = "Standard.Builtins.Main.Boolean"; public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 074349e4d231..45b39c9c8161 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -158,36 +158,6 @@ type Debug eval : Text -> Any eval expression = @Builtin_Method "Debug.eval" -# The type that subsumes all types. -type Any - - ## Any is the universal top-type, with all other types being subsumed by it. - - If a value of type Any is expected in a given location, _any value_ can - be used in that position. - @Builtin_Type - type Any - - ## PRIVATE - - Executes the provided handler on a dataflow error, or executes as - identity on a non-error value. - - Arguments: - - handler: The function to call on this if it is an error value. - catch_primitive : (Error -> Any) -> Any - catch_primitive handler = @Builtin_Method "Any.catch" - - ## Generic conversion of an arbitrary Enso value to a corresponding textual - representation. - - > Example - Getting a textual representation of the number 7. - - 7.to_text - to_text : Text - to_text = @Builtin_Method "Any.to_text" - ## Dataflow errors. type Error diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index 1502c3b3fe91..ef9c098fe3f4 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -27,6 +27,7 @@ class RuntimeStubsGenerator(builtins: Builtins) { if (tp.builtinType) { val builtinType = builtins.getBuiltinType(tp.name) scope.registerBuiltinConstructor(builtinType) + builtinType.setShadowDefinitions(scope) } else { scope.registerConstructor(constructor) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index 1aec13fc1fd9..2dbd0c040bca 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -7,11 +7,7 @@ import org.enso.compiler.data.BindingsMap import org.enso.compiler.exception.CompilerError import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis -import org.enso.compiler.pass.desugar.{ - ComplexType, - FunctionBinding, - GenerateMethodBodies -} +import org.enso.compiler.pass.desugar.{ComplexType, FunctionBinding, GenerateMethodBodies} import scala.annotation.unused diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 7b9657b2a1cf..4dbafb53b698 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -44,7 +44,7 @@ class InteropTest extends InterpreterTest { "work with oversaturated calls on unresolved methods returned from functions" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Any import all | |Any.method = this | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 733f6e997d32..37b7058632de 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala @@ -87,7 +87,7 @@ class MethodsTest extends InterpreterTest { "be definable as blocks without arguments" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Any import all | |Any.method = | x = this * this @@ -126,6 +126,7 @@ class MethodsTest extends InterpreterTest { "be callable for any type when defined on Any" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Any import all | |type Foo |type Bar diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index 9ad963805dbb..c6cb47f6e81e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -91,7 +91,7 @@ class PolyglotTest extends InterpreterTest { count shouldEqual "FAIL" } - "fail to match on Polyglot type case when importing Polyglot module" in { + "fail to match on Polyglot type case when only importing Polyglot module" in { val code = """import Standard.Base.Polyglot |from Standard.Builtins import IO, Nothing @@ -125,22 +125,5 @@ class PolyglotTest extends InterpreterTest { count shouldEqual "OK" } - "match on qualified name of the Polyglot type from Polyglot module" in { - val code = - """import Standard.Base.Polyglot - |from Standard.Builtins import IO, Nothing - |polyglot java import java.util.Random - | - |main = - | random_gen = Random.new - | case random_gen of - | Polyglot.Polyglot -> IO.println "OK" - | _ -> IO.println "FAIL" - |""".stripMargin - eval(code) - val count :: Nil = consumeOut - count shouldEqual "OK" - } - } } From 9dbfa06d46254331660728563123bcabaf498ab8 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 11 Apr 2022 17:57:04 +0200 Subject: [PATCH 12/73] Move Boolean to stdlib Mostly c&p, and occassional fix for imports/renaming. --- .../Base/0.0.0-dev/src/Data/List.enso | 1 + .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 5 +- .../BooleanConstructorBranchNode.java | 19 ++- .../builtin/bool/CompareToNode.java | 2 +- .../expression/builtin/bool/EqualsNode.java | 2 +- .../expression/constant/ConstructorNode.java | 6 +- .../interpreter/runtime/builtin/Builtins.java | 51 +++++--- .../dispatch/DefaultBooleanExports.java | 30 ++--- .../runtime/src/main/resources/Builtins.enso | 115 ------------------ .../enso/compiler/codegen/IrToTruffle.scala | 10 +- .../test/semantic/SystemProcessTest.scala | 24 ++++ .../scala/org/enso/std/test/BooleanTest.scala | 7 ++ 12 files changed, 107 insertions(+), 165 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index f28e03968131..5d485e91394a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,5 +1,6 @@ from Standard.Builtins import all from Standard.Builtins export Nil, Cons +from Standard.Base.Data.Boolean import True, False ## The basic cons-list type. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 87918c766644..4cefac4c36a9 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -1,5 +1,6 @@ import project.Data.Any import project.Data.Array +import project.Data.Boolean import project.Data.Interval import project.Data.Json import project.Data.List @@ -29,8 +30,9 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Any, True, False, Cons, Boolean, Arithmetic_Error +from Standard.Builtins import Nothing, Number, Integer, Cons, Arithmetic_Error +#export project.Data.Boolean export project.Data.Interval export project.Data.Json export project.Data.Locale @@ -50,6 +52,7 @@ export project.Warning from project.Data.Array export Array from project.Data.Any export all +from project.Data.Boolean export all from project.Data.List export Nil, Cons from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java index b849d32f6707..331bb15df7c4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java @@ -19,11 +19,14 @@ public abstract class BooleanConstructorBranchNode extends BranchNode { private final AtomConstructor falseCons; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - BooleanConstructorBranchNode(Bool bool, RootCallTarget branch) { + BooleanConstructorBranchNode(AtomConstructor bool, + AtomConstructor trueAtom, + AtomConstructor falseAtom, + RootCallTarget branch) { super(branch); - this.boolCons = bool.getBool(); - this.trueCons = bool.getTrue(); - this.falseCons = bool.getFalse(); + this.boolCons = bool; + this.trueCons = trueAtom; + this.falseCons = falseAtom; } /** @@ -33,8 +36,12 @@ public abstract class BooleanConstructorBranchNode extends BranchNode { * @param branch the expression to be executed if (@code matcher} matches * @return a node for matching in a case expression */ - public static BooleanConstructorBranchNode build(Bool bool, RootCallTarget branch) { - return BooleanConstructorBranchNodeGen.create(bool, branch); + public static BooleanConstructorBranchNode build( + AtomConstructor bool, + AtomConstructor trueAtom, + AtomConstructor falseAtom, + RootCallTarget branch) { + return BooleanConstructorBranchNodeGen.create(bool,trueAtom, falseAtom, branch); } @Specialization diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index 142d6b4bf57c..7d7859a0a0c5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -36,7 +36,7 @@ Atom doBoolean( Atom doOther( Boolean _this, Object that) { CompilerDirectives.transferToInterpreter(); - var bool = Context.get(this).getBuiltins().bool().getBool().newInstance(); + var bool = Context.get(this).getBuiltins().bool().newInstance(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java index 1c0dcd0b0095..97f137d994c2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java @@ -39,6 +39,6 @@ boolean doOther(Object _this, Object that) { } AtomConstructor getBooleanConstructor() { - return Context.get(this).getBuiltins().bool().getBool(); + return Context.get(this).getBuiltins().bool(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java index 98622458b716..3a0bb3f0291e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java @@ -34,11 +34,11 @@ public static ConstructorNode build(AtomConstructor constructor) { */ @Specialization Object doExecute(VirtualFrame frame) { - var bool = Context.get(this).getBuiltins().bool(); - if (constructor == bool.getTrue()) { + var builtins = Context.get(this).getBuiltins(); + if (constructor == builtins.trueAtom()) { return true; } - if (constructor == bool.getFalse()) { + if (constructor == builtins.falseAtom()) { return false; } if (constructor.getArity() == 0) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 02c0672d846f..f4903422aa7e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -19,7 +19,6 @@ import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; -import org.enso.interpreter.node.expression.builtin.error.CatchAnyMethodGen; import org.enso.interpreter.node.expression.builtin.error.CatchPanicMethodGen; import org.enso.interpreter.node.expression.builtin.error.CaughtPanicConvertToDataflowErrorMethodGen; import org.enso.interpreter.node.expression.builtin.error.GetAttachedStackTraceMethodGen; @@ -38,8 +37,6 @@ import org.enso.interpreter.node.expression.builtin.state.GetStateMethodGen; import org.enso.interpreter.node.expression.builtin.state.PutStateMethodGen; import org.enso.interpreter.node.expression.builtin.state.RunStateMethodGen; -import org.enso.interpreter.node.expression.builtin.text.AnyToDisplayTextMethodGen; -import org.enso.interpreter.node.expression.builtin.text.AnyToTextMethodGen; import org.enso.interpreter.node.expression.builtin.thread.WithInterruptHandlerMethodGen; import org.enso.interpreter.node.expression.builtin.unsafe.SetAtomFieldMethodGen; import org.enso.interpreter.runtime.Context; @@ -79,7 +76,6 @@ public static class Debug { private final AtomConstructor panic; private final AtomConstructor caughtPanic; - private final Bool bool; private final DataflowError dataflowError; private final Error error; private final Module module; @@ -103,7 +99,6 @@ public Builtins(Context context) { builtinNodes = new HashMap<>(); builtinTypes = new HashMap<>(); - bool = new Bool(language, scope); debug = new AtomConstructor("Debug", scope).initializeFields(); dataflowError = new DataflowError(language, scope); Warning.initWarningMethods(language, scope); @@ -203,6 +198,9 @@ public Builtins(Context context) { builtinConstructors.add("Ref"); builtinConstructors.add("Array"); builtinConstructors.add("Any"); + builtinConstructors.add("Boolean"); + builtinConstructors.add("True"); + builtinConstructors.add("False"); initBuiltinTypes(builtinConstructors, scope, language); } @@ -211,17 +209,19 @@ public void initBuiltinTypes(List constrs, ModuleScope scope, Language l BuiltinAtomConstructor atom = new BuiltinAtomConstructor(constr, scope).initializeFields(); builtinTypes.put(constr, atom); Map> methods = builtinNodes.get(constr); - methods.forEach((methodName, clazz) -> { - Optional fun; - try { - Method meth = clazz.getMethod("makeFunction", Language.class); - fun = Optional.ofNullable((Function) meth.invoke(null, language)); - } catch (Exception e) { - e.printStackTrace(); - fun = Optional.empty(); - } - fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); - }); + if (methods != null) { + methods.forEach((methodName, clazz) -> { + Optional fun; + try { + Method meth = clazz.getMethod("makeFunction", Language.class); + fun = Optional.ofNullable((Function) meth.invoke(null, language)); + } catch (Exception e) { + e.printStackTrace(); + fun = Optional.empty(); + } + fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); + }); + } } } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ @@ -407,11 +407,22 @@ public Number number() { return number; } - /** @return the Boolean part of builtins. */ - public Bool bool() { - return bool; + /** @return the Boolean constructor. */ + public AtomConstructor bool() { + return builtinTypes.get("Boolean"); } + /** @return the True constructor. */ + public AtomConstructor trueAtom() { + return builtinTypes.get("True"); + } + + /** @return the False constructor. */ + public AtomConstructor falseAtom() { + return builtinTypes.get("False"); + } + + /** @return the builtin Error types container. */ public Error error() { return error; @@ -506,7 +517,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.ARRAY: return array().newInstance(); case Constants.BOOLEAN: - return bool.getBool().newInstance(); + return bool().newInstance(); case Constants.DECIMAL: return number.getDecimal().newInstance(); case Constants.ERROR: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java index 49beda2b9e9c..9ae227ab139b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java @@ -6,7 +6,7 @@ import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Bool; +import org.enso.interpreter.runtime.builtin.Builtins; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; @@ -32,22 +32,22 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function resolveMethodOnPrimBoolean(UnresolvedSymbol symbol) { Context context = getContext(); - Bool bool = context.getBuiltins().bool(); - if (symbol.resolveFor(bool.getFalse()) != null) { + Builtins builtins = context.getBuiltins(); + if (symbol.resolveFor(builtins.falseAtom()) != null) { return null; } - if (symbol.resolveFor(bool.getTrue()) != null) { + if (symbol.resolveFor(builtins.trueAtom()) != null) { return null; } - return symbol.resolveFor(bool.getBool(), context.getBuiltins().any()); + return symbol.resolveFor(builtins.bool(), context.getBuiltins().any()); } @CompilerDirectives.TruffleBoundary static Function resolveMethodOnBool(boolean self, UnresolvedSymbol symbol) { Context context = getContext(); - Bool bool = context.getBuiltins().bool(); - AtomConstructor cons = self ? bool.getTrue() : bool.getFalse(); - return symbol.resolveFor(cons, bool.getBool(), context.getBuiltins().any()); + Builtins builtins = context.getBuiltins(); + AtomConstructor cons = self ? builtins.trueAtom() : builtins.falseAtom(); + return symbol.resolveFor(cons, builtins.bool(), context.getBuiltins().any()); } static Context getContext() { @@ -130,22 +130,22 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function resolveMethodOnPrimBoolean(AtomConstructor target, UnresolvedConversion conversion) { Context context = Context.get(null); - Bool bool = context.getBuiltins().bool(); - if (conversion.resolveFor(target, bool.getFalse()) != null) { + Builtins builtins = context.getBuiltins(); + if (conversion.resolveFor(target, builtins.falseAtom()) != null) { return null; } - if (conversion.resolveFor(target, bool.getTrue()) != null) { + if (conversion.resolveFor(target, builtins.trueAtom()) != null) { return null; } - return conversion.resolveFor(target, bool.getBool(), context.getBuiltins().any()); + return conversion.resolveFor(target, builtins.bool(), context.getBuiltins().any()); } @CompilerDirectives.TruffleBoundary static Function resolveMethodOnBool(boolean self, AtomConstructor target, UnresolvedConversion conversion) { Context context = Context.get(null); - Bool bool = context.getBuiltins().bool(); - AtomConstructor cons = self ? bool.getTrue() : bool.getFalse(); - return conversion.resolveFor(target, cons, bool.getBool(), context.getBuiltins().any()); + Builtins builtins = context.getBuiltins(); + AtomConstructor cons = self ? builtins.trueAtom() : builtins.falseAtom(); + return conversion.resolveFor(target, cons, builtins.bool(), context.getBuiltins().any()); } static Context getContext() { diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 45b39c9c8161..eaf0bc33c16c 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -4,121 +4,6 @@ # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. -## Booleans. -type Boolean - - ## A type with only two possible values. - - The boolean type represents the two truth values of boolean logic. It is - primarily used for control-flow. - @Builtin_Type - type Boolean - - ## Compares two booleans for equality. - - Arguments: - - that: The boolean to compare this with. - - > Example - Comparing True to False to get False. - - True == False - == : Boolean -> Boolean - == that = @Builtin_Method "Boolean.==" - - ## Computes the logical and (conjunction) of two booleans. - - Arguments: - - that: The boolean to compute the conjunction of this with. - - ! Short Circuiting - This method is not implemented in a short-circuiting manner. This means - that even if this is False, it will also evaluate that. This is - for performance. - - > Example - Computing the conjunction of False and True (to get False). - - False && True - && : Boolean -> Boolean - && that = @Builtin_Method "Boolean.&&" - - ## Computes the logical or (disjunction) of two booleans. - - Arguments: - - that: The boolean to compute the disjunction of this with. - - ! Short Circuiting - This methid is not implemented in a short-circuiting manner. This means - that even if this is True, it will also evaluate that. This is - for performance. - - > Example - Computing the disjunction of True and False (to get True). - - True || False - || : Boolean -> Boolean - || that = @Builtin_Method "Boolean.||" - - ## Computes the logical negation of this. - - > Example - Negating True to get False. - - True.not - not : Boolean - not = @Builtin_Method "Boolean.not" - - ## Generates a human-readable text representation of the boolean. - - > Example - Converting the value True to text. - - True.to_text - to_text : Text - to_text = @Builtin_Method "Boolean.to_text" - - ## The if-then-else control flow operator that executes one of two branches - based on a conditional. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - on_false: The computation to evaluate if this evaluates to False. - - Both of the arguments to this method are _lazy_, meaning that they will - only be evaluated if they are needed (based on the condition). - - > Example - Telling the user if a number 27 is divisible by three. - - if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" - if_then_else : Any -> Any -> Any - if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - - ## The if-then control flow operator that executes a branch if the condition - is true, and otherwise returns Nothing. - - Arguments: - - on_true: The computation to evaluate if this evaluates to True. - - The argument to this method is _lazy_, meaning that it will only be - evaluated if the this evaluates to True. - - > Example - Printing a message to the user only if a number is divisible by three. - - if (27 % 3) == 0 then IO.println "Fizz" - if_then : Any -> Any | Nothing - if_then ~on_true = @Builtin_Method "Boolean.if_then" - -## The constructor for the value True. -@Builtin_Type -type True - -## The constructor for the value False. -@Builtin_Type -type False - ## Debug utilities. type Debug diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index a878c946a239..fc2637ede0ba 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -795,17 +795,21 @@ class IrToTruffle( val any = context.getBuiltins.any val array = context.getBuiltins.array val bool = context.getBuiltins.bool + val builtinTrue = context.getBuiltins.trueAtom + val builtinFalse = context.getBuiltins.falseAtom val number = context.getBuiltins.number val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text val branchNode: BranchNode = - if (atomCons == bool.getTrue) { + if (atomCons == builtinTrue) { BooleanBranchNode.build(true, branchCodeNode.getCallTarget) - } else if (atomCons == bool.getFalse) { + } else if (atomCons == builtinFalse) { BooleanBranchNode.build(false, branchCodeNode.getCallTarget) - } else if (atomCons == bool.getBool) { + } else if (atomCons == bool) { BooleanConstructorBranchNode.build( bool, + builtinTrue, + builtinFalse, branchCodeNode.getCallTarget ) } else if (atomCons == text.getText) { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index b79f6a1beb7b..95fe1b2279e3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -20,6 +20,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" Array.empty "" False False False @@ -34,6 +35,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_1 "/c") "" False False False @@ -48,6 +50,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all |main = System.create_process "nonexistentcommandxyz" Array.empty "" False False False |""".stripMargin @@ -61,6 +64,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "ls" (Array.new_1 "--gibberish") "" False False False @@ -76,6 +80,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "exit 7") "" False False False @@ -91,6 +96,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; echo $line") "" True True True @@ -107,6 +113,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "" True True True @@ -124,6 +131,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "wc -c") "" True True True @@ -140,6 +148,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "42") "" True True True @@ -156,6 +165,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -172,6 +182,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "9") "" True True True @@ -187,6 +198,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -202,6 +214,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; printf $line") "hello" False False False @@ -217,6 +230,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "hello" False False False @@ -232,6 +246,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False True True @@ -247,6 +262,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False True True @@ -262,6 +278,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\x01\x0F\x10'") "" False True True @@ -277,6 +294,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False False False @@ -293,6 +311,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False False False @@ -309,6 +328,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False True True @@ -324,6 +344,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False True True @@ -339,6 +360,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\xCA\xFE\xBA\xBE' 1>&2") "" False True True @@ -354,6 +376,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False False False @@ -369,6 +392,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { val code = """from Standard.Builtins import all |import Standard.Base.Data.Array + |from Standard.Base.Data.Boolean import all | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False False False diff --git a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala index 71f9058381f6..d06a02b97c76 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala @@ -12,6 +12,7 @@ class BooleanTest extends InterpreterTest { "support if_then_else" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |main = | if True then IO.println "true when true" else IO.println "false when true" @@ -24,6 +25,7 @@ class BooleanTest extends InterpreterTest { "support overriding methods on boolean" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |Boolean.isTrue = this | @@ -40,6 +42,7 @@ class BooleanTest extends InterpreterTest { "support pattern matching" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |to_num b = case b of | True -> 1 @@ -55,6 +58,7 @@ class BooleanTest extends InterpreterTest { "support per-constructor method overloads" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |True.to_num = 1 |False.to_num = 2 @@ -67,6 +71,7 @@ class BooleanTest extends InterpreterTest { "support per-single-constructor method overloads" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |Boolean.to_num = 2 |True.to_num = 1 @@ -79,6 +84,7 @@ class BooleanTest extends InterpreterTest { "support logical AND and OR operators" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |main = | IO.println True&&False @@ -94,6 +100,7 @@ class BooleanTest extends InterpreterTest { "support negation" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Boolean import all | |main = | IO.println True.not From c42b0924e0f175b32af1ab98cfdd06d1aa91346d Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 11 Apr 2022 23:22:21 +0200 Subject: [PATCH 13/73] Missing Booleans.enso from last commit --- .../Base/0.0.0-dev/src/Data/Boolean.enso | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso new file mode 100644 index 000000000000..72b94aeaf356 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso @@ -0,0 +1,114 @@ +## Booleans. +type Boolean + + ## A type with only two possible values. + + The boolean type represents the two truth values of boolean logic. It is + primarily used for control-flow. + @Builtin_Type + type Boolean + + ## Compares two booleans for equality. + + Arguments: + - that: The boolean to compare this with. + + > Example + Comparing True to False to get False. + + True == False + == : Boolean -> Boolean + == that = @Builtin_Method "Boolean.==" + + ## Computes the logical and (conjunction) of two booleans. + + Arguments: + - that: The boolean to compute the conjunction of this with. + + ! Short Circuiting + This method is not implemented in a short-circuiting manner. This means + that even if this is False, it will also evaluate that. This is + for performance. + + > Example + Computing the conjunction of False and True (to get False). + + False && True + && : Boolean -> Boolean + && that = @Builtin_Method "Boolean.&&" + + ## Computes the logical or (disjunction) of two booleans. + + Arguments: + - that: The boolean to compute the disjunction of this with. + + ! Short Circuiting + This methid is not implemented in a short-circuiting manner. This means + that even if this is True, it will also evaluate that. This is + for performance. + + > Example + Computing the disjunction of True and False (to get True). + + True || False + || : Boolean -> Boolean + || that = @Builtin_Method "Boolean.||" + + ## Computes the logical negation of this. + + > Example + Negating True to get False. + + True.not + not : Boolean + not = @Builtin_Method "Boolean.not" + + ## Generates a human-readable text representation of the boolean. + + > Example + Converting the value True to text. + + True.to_text + to_text : Text + to_text = @Builtin_Method "Boolean.to_text" + + ## The if-then-else control flow operator that executes one of two branches + based on a conditional. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + - on_false: The computation to evaluate if this evaluates to False. + + Both of the arguments to this method are _lazy_, meaning that they will + only be evaluated if they are needed (based on the condition). + + > Example + Telling the user if a number 27 is divisible by three. + + if (27 % 3) == 0 then IO.println "Yes" else IO.println "No" + if_then_else : Any -> Any -> Any + if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" + + ## The if-then control flow operator that executes a branch if the condition + is true, and otherwise returns Nothing. + + Arguments: + - on_true: The computation to evaluate if this evaluates to True. + + The argument to this method is _lazy_, meaning that it will only be + evaluated if the this evaluates to True. + + > Example + Printing a message to the user only if a number is divisible by three. + + if (27 % 3) == 0 then IO.println "Fizz" + if_then : Any -> Any | Nothing + if_then ~on_true = @Builtin_Method "Boolean.if_then" + +## The constructor for the value True. +@Builtin_Type +type True + +## The constructor for the value False. +@Builtin_Type +type False From fb10830abeee37e1bd6849b3c757c408eaec17c6 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 11 Apr 2022 23:24:29 +0200 Subject: [PATCH 14/73] Simplify builtins metadata generation Rather than writing multiple tiny metadata files per each builtin we now generate a single file with all information. This simplifies the logic of reading that data in builtins a lot. --- .../interpreter/runtime/builtin/Builtins.java | 89 ++++++++----------- .../dsl/BuiltinsMetadataProcessor.java | 72 +++++++++++++++ .../enso/interpreter/dsl/MethodProcessor.java | 25 ++---- .../dsl/model/MethodDefinition.java | 4 +- 4 files changed, 120 insertions(+), 70 deletions(-) create mode 100644 lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index f4903422aa7e..f0789a1d1b96 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -264,58 +264,50 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) private void readBuiltinsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); + List lines; FileSystem fs = null; - Stream builtinMetaPath; try { URI resource = classLoader.getResource(MethodDefinition.META_PATH).toURI(); fs = initFileSystem(resource); - builtinMetaPath = Files.walk(Paths.get(resource)).flatMap(p -> acceptMetadataFiles(p)); + lines = Files.readAllLines(Paths.get(resource), StandardCharsets.UTF_8); } catch (Exception ioe) { + lines = new ArrayList<>(); ioe.printStackTrace(); - builtinMetaPath = Stream.empty(); } - builtinMetaPath.forEach(metaPath -> { - List lines; - try { - lines = Files.readAllLines(metaPath, StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - lines = new ArrayList<>(); - } - lines.forEach(line -> { - String[] builtinMeta = line.split(":"); - if (builtinMeta.length != 2) { - throw new CompilerError("Invalid builtin metadata in " + metaPath + ": " + line); - } - String[] builtinName = builtinMeta[0].split("\\."); - if (builtinName.length != 2) { - throw new CompilerError("Invalid builtin metadata in " + metaPath + ": " + line); - } - try { - Class clazz = (Class) Class.forName(builtinMeta[1]); - String builtinMethodOwner = builtinName[0]; - String builtinMethodName = builtinName[1]; - scope.getLocalConstructor(builtinMethodOwner).ifPresentOrElse(constr -> { - Map> atomNodes = builtinNodes.get(builtinMethodOwner); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - builtinNodes.put(constr.getName(), atomNodes); - } - atomNodes.put(builtinMethodName, clazz); - }, () -> { - Map> atomNodes = builtinNodes.get(builtinMethodOwner); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - builtinNodes.put(builtinMethodOwner, atomNodes); - } - atomNodes.put(builtinMethodName, clazz); - }); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - }); + + lines.forEach(line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length != 2) { + throw new CompilerError("Invalid builtin metadata in: " + line); + } + String[] builtinName = builtinMeta[0].split("\\."); + if (builtinName.length != 2) { + throw new CompilerError("Invalid builtin metadata in : " + line); + } + try { + Class clazz = (Class) Class.forName(builtinMeta[1]); + String builtinMethodOwner = builtinName[0]; + String builtinMethodName = builtinName[1]; + scope.getLocalConstructor(builtinMethodOwner).ifPresentOrElse(constr -> { + Map> atomNodes = builtinNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + builtinNodes.put(constr.getName(), atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }, () -> { + Map> atomNodes = builtinNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + builtinNodes.put(builtinMethodOwner, atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } }); if (fs != null) { try { @@ -343,13 +335,6 @@ private FileSystem initFileSystem(URI uri) throws IOException } } - private Stream acceptMetadataFiles(Path path) { - if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(MethodDefinition.META_BUILTIN_EXTENSION)) { - return Stream.of(path); - } - return Stream.empty(); - } - public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone Map> atomNodes = builtinNodes.get(atom.getName()); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java new file mode 100644 index 000000000000..3c446aebd046 --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -0,0 +1,72 @@ +package org.enso.interpreter.dsl; + +import org.enso.interpreter.dsl.model.MethodDefinition; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Filer; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.element.TypeElement; +import javax.tools.FileObject; +import javax.tools.StandardLocation; +import java.io.IOException; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { + private final Map> builtinMethods = new HashMap<>(); + + @Override + public final boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.errorRaised()) { + return false; + } + if (roundEnv.processingOver()) { + try { + storeBuiltinMetadata(MethodDefinition.META_PATH); + } catch (IOException e) { + e.printStackTrace(); + } + builtinMethods.clear(); + return true; + } else { + return handleProcess(annotations, roundEnv); + } + } + + /** + * The regular body of {@link #process}. + * Called during regular rounds if there are no outstanding errors. + * In the last round, one of the processors will dump all builtin metadata + * @param annotations as in {@link #process} + * @param roundEnv as in {@link #process} + * @return as in {@link #process} + */ + protected abstract boolean handleProcess(Set annotations, RoundEnvironment roundEnv); + + private void storeBuiltinMetadata(String path) throws IOException { + FileObject res = processingEnv.getFiler().createResource( + StandardLocation.CLASS_OUTPUT, "", + path + ); + Writer writer = res.openWriter(); + try { + for (Filer f: builtinMethods.keySet()) { + for (Map.Entry entry : builtinMethods.get(f).entrySet()) { + writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); + } + } + } finally { + writer.close(); + } + } + protected void registerBuiltinMethod(Filer f, String name, String clazzName) { + Map methods = builtinMethods.get(f); + if (methods == null) { + methods = new HashMap<>(); + builtinMethods.put(f, methods); + } + methods.put(name, clazzName); + } +} diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index a899f3c78463..cce1ab116a97 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -22,7 +22,7 @@ @SupportedAnnotationTypes("org.enso.interpreter.dsl.BuiltinMethod") @SupportedSourceVersion(SourceVersion.RELEASE_11) @AutoService(Processor.class) -public class MethodProcessor extends AbstractProcessor { +public class MethodProcessor extends BuiltinsMetadataProcessor { /** * Processes annotated elements, generating code for each of them. @@ -32,7 +32,7 @@ public class MethodProcessor extends AbstractProcessor { * @return {@code true} */ @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { + public boolean handleProcess(Set annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); for (Element elt : annotatedElements) { @@ -57,13 +57,19 @@ public boolean process(Set annotations, RoundEnvironment if (executeMethod == null) continue; String pkgName = processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); + MethodDefinition def = new MethodDefinition(pkgName, element, executeMethod); if (!def.validate(processingEnv)) { continue; } try { generateCode(def); - registerBuiltinMethod(def, element); + String tpe = def.getType().toLowerCase(); + if (tpe.isEmpty()) { + throw new InternalError("Type of the BuiltinMethod cannot be empty in: " + def.getClassName()); + } + String fullClassName = def.getPackageName() + "." + def.getClassName(); + registerBuiltinMethod(processingEnv.getFiler(), def.getDeclaredName(), fullClassName); } catch (IOException e) { e.printStackTrace(); } @@ -94,19 +100,6 @@ public boolean process(Set annotations, RoundEnvironment "org.enso.interpreter.runtime.state.Stateful", "org.enso.interpreter.runtime.type.TypesGen"); - private void registerBuiltinMethod(MethodDefinition methodDefinition, Element element) throws IOException { - String tpe = methodDefinition.getType().toLowerCase(); - if (tpe.isEmpty()) { - throw new InternalError("Type of the BuiltinMethod cannot be empty"); - } - FileObject res = processingEnv.getFiler().createResource( - StandardLocation.CLASS_OUTPUT, "", - MethodDefinition.META_PATH + "/" + tpe + "/" + methodDefinition.getClassName() + MethodDefinition.META_BUILTIN_EXTENSION, element - ); - String fullClassName = methodDefinition.getPackageName() + "." + methodDefinition.getClassName(); - res.openWriter().append(methodDefinition.getDeclaredName() + ":" + fullClassName+"\n").close(); - } - private void generateCode(MethodDefinition methodDefinition) throws IOException { JavaFileObject gen = processingEnv.getFiler().createSourceFile(methodDefinition.getQualifiedName()); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index 0a9393be24ad..6d11f7581d42 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -13,8 +13,8 @@ public class MethodDefinition { private static final String STATEFUL = "org.enso.interpreter.runtime.state.Stateful"; public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; - public static final String META_PATH = "META-INF" + "/" + NODE_PKG.replace('.', '/'); - public static final String META_BUILTIN_EXTENSION = ".builtin"; + public static final String META_PATH = + "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/Builtins.metadata"; private final String packageName; private final String originalClassName; From fb666c19c7a10833badca3d8274b7a2370be2f1b Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 12 Apr 2022 11:50:37 +0200 Subject: [PATCH 15/73] Cleanup --- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 1 - .../caseexpr/BranchNodeFactory.java | 16 -------- .../callable/atom/BuiltinAtomConstructor.java | 10 +++-- .../runtime/scope/ModuleScope.java | 39 ------------------- .../codegen/RuntimeStubsGenerator.scala | 4 +- 5 files changed, 9 insertions(+), 61 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 4cefac4c36a9..b1a253ef0d2a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -32,7 +32,6 @@ import project.Warning from Standard.Builtins import Nothing, Number, Integer, Cons, Arithmetic_Error -#export project.Data.Boolean export project.Data.Interval export project.Data.Json export project.Data.Locale diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java deleted file mode 100644 index a9e471708c21..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BranchNodeFactory.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.enso.interpreter.node.controlflow.caseexpr; - -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import com.oracle.truffle.api.RootCallTarget; - -/** - * BranchNodeFactory is a SAM-type to allow for storing the mapping between - * AtomConstructors and corresponding BranchNode. - * - * SAM-type is necessary because types like - * `PolyglotBranchNode.build _` - - */ -public interface BranchNodeFactory { - BranchNode create(AtomConstructor atomConstructor, RootCallTarget target); -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java index c1454b01cc65..ea4e508241d6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java @@ -12,16 +12,20 @@ public class BuiltinAtomConstructor extends AtomConstructor { private ModuleScope shadowDefinitions; /** - * Creates a new Atom constructor for a given name. The constructor is not valid until {@link - * AtomConstructor#initializeFields(LocalScope, ExpressionNode[], ExpressionNode[], ArgumentDefinition...)} is called. + * Creates a new Atom constructor for a given name for a BuiltinType. The constructor is not valid until {@link + * BuiltinAtomConstructor#initializeFields(ArgumentDefinition...)} is called. * * @param name the name of the Atom constructor - * @param definitionScope the scope in which this constructor was defined + * @param definitionScope the scope in which this constructor was defined (builtin scope) */ public BuiltinAtomConstructor(String name, ModuleScope definitionScope) { super(name, definitionScope); } + /** + * Additional scope for BuiltinTypes pointing to an auxiliary scope in standard library + * @param scope the scope of definitions in standard library + */ public void setShadowDefinitions(ModuleScope scope) { if (shadowDefinitions != null) { throw new CompilerError("cannot set shadow definitions twice"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index ac55f764781c..2ac93d0a7714 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -45,15 +45,6 @@ public void registerConstructor(AtomConstructor constructor) { constructors.put(constructor.getName(), constructor); } - public void registerBuiltinConstructor(AtomConstructor constructor) { - registerConstructor(constructor); - builtins.add(constructor); - } - - public boolean isBuiltin(AtomConstructor constructor) { - return builtins.contains(constructor); - } - /** @return the associated type of this module. */ public AtomConstructor getAssociatedType() { return associatedType; @@ -208,36 +199,6 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { return definedWithAtom; } - // Additional check for Builtin_Type's - // Consider a module Foo.enso in std library:: - // type Foo - // @Builtin_Type - // type Foo - // length = 0 - // new size = @Builtin_Method ... - // - // a) you want to be able to match on it like - // ``` - // case x of - // Foo -> ... - // ``` - // and not - // ``` - // case x of - // Foo.Foo -> ... - // ``` - // and yet you still want to be able to call - // `Foo.new` - // Enhancing the method definition lookup for Builtin_Types allows you to avoid - // introducing additional import statements, especially for atom Builtin_Type. - AtomConstructor moduleType = atom.getDefinitionScope().associatedType; - if (atom != moduleType && atom.getDefinitionScope().isBuiltin(atom)) { - definedWithAtom = atom.getDefinitionScope().getMethodMapFor(moduleType).get(lowerName); - if (definedWithAtom != null) { - return definedWithAtom; - } - } - Function definedHere = getMethodMapFor(atom).get(lowerName); if (definedHere != null) { return definedHere; diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index ef9c098fe3f4..32e645ebc80b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -23,12 +23,12 @@ class RuntimeStubsGenerator(builtins: Builtins) { "Non-parsed module used in stubs generator" ) localBindings.types.foreach { tp => - val constructor = new AtomConstructor(tp.name, scope) if (tp.builtinType) { val builtinType = builtins.getBuiltinType(tp.name) - scope.registerBuiltinConstructor(builtinType) + scope.registerConstructor(builtinType) builtinType.setShadowDefinitions(scope) } else { + val constructor = new AtomConstructor(tp.name, scope) scope.registerConstructor(constructor) } } From 1dc959421016b31b773f0036be3ac7180122c91d Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 12 Apr 2022 14:16:08 +0200 Subject: [PATCH 16/73] Simplify resource reading Reading resource as a stream rather than as a file allows us to remove the need to initialize FileSystem. --- .../interpreter/runtime/builtin/Builtins.java | 38 +++---------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index f0789a1d1b96..d3e44cb08a4c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -2,13 +2,14 @@ import com.oracle.truffle.api.CompilerDirectives; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.lang.reflect.Method; -import java.net.URI; import java.nio.charset.StandardCharsets; -import java.nio.file.*; import java.util.*; -import java.util.stream.Stream; +import java.util.stream.Collectors; import org.enso.compiler.Passes; import org.enso.compiler.context.FreshNameSupply; @@ -265,11 +266,8 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) private void readBuiltinsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; - FileSystem fs = null; - try { - URI resource = classLoader.getResource(MethodDefinition.META_PATH).toURI(); - fs = initFileSystem(resource); - lines = Files.readAllLines(Paths.get(resource), StandardCharsets.UTF_8); + try (InputStream resource = classLoader.getResourceAsStream(MethodDefinition.META_PATH)) { + lines = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); } catch (Exception ioe) { lines = new ArrayList<>(); ioe.printStackTrace(); @@ -309,30 +307,6 @@ private void readBuiltinsMetadata(ModuleScope scope) { e.printStackTrace(); } }); - if (fs != null) { - try { - fs.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private FileSystem initFileSystem(URI uri) throws IOException - { - // Returning null ensures that we use the default one and at the same time we don't attempt - // to close it. - try { - FileSystems.getFileSystem(uri); - return null; - } catch (IllegalArgumentException iae) { - // file: schema doesn't like non-/ path but that's fine, it means the default file system is already setup - return null; - } catch (FileSystemNotFoundException e) { - Map env = new HashMap<>(); - env.put("create", "true"); - return FileSystems.newFileSystem(uri, env); - } } public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { From a588c805c666098da4a5ef0dc5c165ef06b80f6b Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 12 Apr 2022 23:37:16 +0200 Subject: [PATCH 17/73] Move List to stdlib Move builtin types Cons & Nil to stdlib List module. Mostly c&p, also preparing for getting rid of temp `builtinConstructors` list for initialization of builtin types. --- .../Base/0.0.0-dev/src/Data/List.enso | 16 ++++- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../interpreter/runtime/builtin/Builtins.java | 71 +++++++++++++------ .../runtime/src/main/resources/Builtins.enso | 15 ---- .../interpreter/test/semantic/CaseTest.scala | 4 +- .../test/semantic/CodeLocationsTest.scala | 24 +++---- .../test/semantic/ConstructorsTest.scala | 11 +-- .../test/semantic/ExpressionIdTest.scala | 16 ++--- .../test/semantic/GroupingTest.scala | 2 +- .../semantic/LambdaShorthandArgsTest.scala | 2 +- .../test/semantic/LambdaTest.scala | 2 +- .../test/semantic/MethodsTest.scala | 4 +- .../test/semantic/PatternMatchTest.scala | 18 ++--- .../interpreter/test/semantic/StateTest.scala | 1 + .../interpreter/test/semantic/TextTest.scala | 1 + 15 files changed, 108 insertions(+), 81 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 5d485e91394a..59a7970cfeff 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -12,9 +12,21 @@ from Standard.Base.Data.Boolean import True, False > Example A list containing the elements `1`, `2`, and `3`, in this order is: Cons 1 (Cons 2 (Cons 3 Nil)) +## Cons lists. type List - Nil - Cons + + ## The type that indicates the end of a cons list. + @Builtin_Type + type Nil + + ## A cons cell for a cons list. + + Arguments: + - head: The element at this position in the list. + - tail: The rest of the list. + @Builtin_Type + type Cons head tail + ## Computes the number of elements in the list. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index b1a253ef0d2a..8f63999427b2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -30,7 +30,7 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Cons, Arithmetic_Error +from Standard.Builtins import Nothing, Number, Integer, Arithmetic_Error export project.Data.Interval export project.Data.Json diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index d3e44cb08a4c..d63f37221fe0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -88,6 +88,31 @@ public static class Debug { private final Text text; private final Special special; + private class BuiltinTypeConstr { + private String tpeName; + private String[] paramNames; + + BuiltinTypeConstr(String tpeName) { + this.tpeName = tpeName; + this.paramNames = new String[0]; + } + + BuiltinTypeConstr(String tpeName, String... args) { + this.tpeName = tpeName; + this.paramNames = args; + } + + + public String getTpeName() { + return tpeName; + } + + public String[] getParamNames() { + return paramNames; + } + + } + /** * Creates an instance with builtin methods installed. * @@ -126,12 +151,6 @@ public Builtins(Context context) { text = new Text(language, scope); special = new Special(language); - AtomConstructor nil = new AtomConstructor("Nil", scope).initializeFields(); - AtomConstructor cons = - new AtomConstructor("Cons", scope) - .initializeFields( - new ArgumentDefinition(0, "head", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "tail", ArgumentDefinition.ExecutionMode.EXECUTE)); AtomConstructor io = new AtomConstructor("IO", scope).initializeFields(); AtomConstructor primIo = new AtomConstructor("Prim_Io", scope).initializeFields(); AtomConstructor runtime = new AtomConstructor("Runtime", scope).initializeFields(); @@ -143,8 +162,6 @@ public Builtins(Context context) { scope.registerConstructor(nothing); scope.registerConstructor(function); - scope.registerConstructor(cons); - scope.registerConstructor(nil); scope.registerConstructor(io); scope.registerConstructor(primIo); scope.registerConstructor(panic); @@ -194,23 +211,33 @@ public Builtins(Context context) { // FIXME: should be possible to get rid of hardcoded list of builtin types once we have all of them // stored in metadata files - List builtinConstructors = new ArrayList<>(); - builtinConstructors.add("Polyglot"); - builtinConstructors.add("Ref"); - builtinConstructors.add("Array"); - builtinConstructors.add("Any"); - builtinConstructors.add("Boolean"); - builtinConstructors.add("True"); - builtinConstructors.add("False"); + List builtinConstructors = new ArrayList<>(); + builtinConstructors.add(new BuiltinTypeConstr("Polyglot")); + builtinConstructors.add(new BuiltinTypeConstr("Ref")); + builtinConstructors.add(new BuiltinTypeConstr("Array")); + builtinConstructors.add(new BuiltinTypeConstr("Any")); + builtinConstructors.add(new BuiltinTypeConstr("Boolean")); + builtinConstructors.add(new BuiltinTypeConstr("True")); + builtinConstructors.add(new BuiltinTypeConstr("False")); + builtinConstructors.add(new BuiltinTypeConstr("Cons", "head", "tail")); + builtinConstructors.add(new BuiltinTypeConstr("Nil")); initBuiltinTypes(builtinConstructors, scope, language); } - public void initBuiltinTypes(List constrs, ModuleScope scope, Language language) { - for (String constr: constrs) { - BuiltinAtomConstructor atom = new BuiltinAtomConstructor(constr, scope).initializeFields(); - builtinTypes.put(constr, atom); - Map> methods = builtinNodes.get(constr); + public void initBuiltinTypes(List constrs, ModuleScope scope, Language language) { + for (BuiltinTypeConstr constr: constrs) { + BuiltinAtomConstructor atom = new BuiltinAtomConstructor(constr.getTpeName(), scope); + ArgumentDefinition[] args = new ArgumentDefinition[constr.getParamNames().length]; + String[] paramNames = constr.getParamNames(); + for (int i=0; i> methods = builtinNodes.get(constr.getTpeName()); if (methods != null) { + BuiltinAtomConstructor finalAtom = atom; methods.forEach((methodName, clazz) -> { Optional fun; try { @@ -220,7 +247,7 @@ public void initBuiltinTypes(List constrs, ModuleScope scope, Language l e.printStackTrace(); fun = Optional.empty(); } - fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); + fun.ifPresent(f -> scope.registerMethod(finalAtom, methodName, f)); }); } } diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 8d260f270ad3..1796158ca571 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -1453,21 +1453,6 @@ type Project_Description @Builtin_Type type Nothing -## Cons lists. -type List - - ## The type that indicates the end of a cons list. - @Builtin_Type - type Nil - - ## A cons cell for a cons list. - - Arguments: - - head: The element at this position in the list. - - tail: The rest of the list. - @Builtin_Type - type Cons head tail - ## A representation of the relative ordering between two values. type Ordering diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala index 285ca4139a0a..4abfa7c15b2e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala @@ -15,7 +15,7 @@ class CaseTest extends InterpreterTest { "result in an error if the matched constructor isn't visible" in { val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |main = | x = Cons 0 Nil @@ -32,7 +32,7 @@ class CaseTest extends InterpreterTest { "result in an error if the wrong number of fields are provided" in { val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |main = | x = Cons 0 Nil diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala index e573ab35a820..dd7e486276ed 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala @@ -54,12 +54,12 @@ class CodeLocationsTest extends InterpreterTest { "be correct in applications and method calls" in withLocationsInstrumenter { instrumenter => val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = (2-2 == 0).if_then_else (Cons 5 6) 0 |""".stripMargin - instrumenter.assertNodeExists(42, 36, classOf[ApplicationNode]) - instrumenter.assertNodeExists(67, 8, classOf[ApplicationNode]) + instrumenter.assertNodeExists(38, 36, classOf[ApplicationNode]) + instrumenter.assertNodeExists(63, 8, classOf[ApplicationNode]) eval(code) () } @@ -112,7 +112,7 @@ class CodeLocationsTest extends InterpreterTest { withLocationsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |main = | x = Cons 1 2 @@ -129,10 +129,10 @@ class CodeLocationsTest extends InterpreterTest { | | foo x + foo y |""".stripMargin - instrumenter.assertNodeExists(115, 109, classOf[CaseNode]) - instrumenter.assertNodeExists(161, 7, classOf[ApplicationNode]) - instrumenter.assertNodeExists(181, 9, classOf[AssignmentNode]) - instrumenter.assertNodeExists(218, 5, classOf[ApplicationNode]) + instrumenter.assertNodeExists(121, 109, classOf[CaseNode]) + instrumenter.assertNodeExists(167, 7, classOf[ApplicationNode]) + instrumenter.assertNodeExists(187, 9, classOf[AssignmentNode]) + instrumenter.assertNodeExists(224, 5, classOf[ApplicationNode]) eval(code) () } @@ -265,7 +265,7 @@ class CodeLocationsTest extends InterpreterTest { instrumenter => val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |type MyAtom | @@ -276,9 +276,9 @@ class CodeLocationsTest extends InterpreterTest { | f (Cons (Cons MyAtom Nil) Nil) |""".stripMargin - instrumenter.assertNodeExists(64, 67, classOf[CaseNode]) - instrumenter.assertNodeExists(69, 1, classOf[ReadLocalVariableNode]) - instrumenter.assertNodeExists(112, 3, classOf[IntegerLiteralNode]) + instrumenter.assertNodeExists(70, 67, classOf[CaseNode]) + instrumenter.assertNodeExists(75, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(118, 3, classOf[IntegerLiteralNode]) eval(code) shouldEqual 100 } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index 307150a5f9a1..09faf2a962e3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala @@ -15,7 +15,7 @@ class ConstructorsTest extends InterpreterTest { ): Unit = { "dispatch to the proper match branch" in { val patternMatchingCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | x = Cons 1 Nil @@ -28,7 +28,7 @@ class ConstructorsTest extends InterpreterTest { "work with recursion" in { val testCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | genList = i -> if i == 0 then Nil else Cons i (genList (i - 1)) @@ -43,7 +43,7 @@ class ConstructorsTest extends InterpreterTest { "behave correctly in non-tail positions" in { val testCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | add = x -> y -> x + y @@ -59,7 +59,7 @@ class ConstructorsTest extends InterpreterTest { "accept a catch-all fallback clause" in { val testCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | nil = Nil @@ -72,7 +72,7 @@ class ConstructorsTest extends InterpreterTest { "throw an exception when match fails" in { val testCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | nil = Nil @@ -86,6 +86,7 @@ class ConstructorsTest extends InterpreterTest { "be usable in code, with arbitrary definition order" in { val testCode = """from Standard.Builtins import all + |from Standard.Base.Data.List import all | |type Cons2 a b | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala index 4d3bc21a6c8c..4243b5bda552 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala @@ -38,13 +38,13 @@ class ExpressionIdTest extends InterpreterTest { "be correct in applications and method calls" in withIdsInstrumenter { instrumenter => val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = (2-2 == 0).if_then_else (Cons 5 6) 0 |""".stripMargin val meta = new Metadata - val id1 = meta.addItem(42, 36) - val id2 = meta.addItem(67, 8) + val id1 = meta.addItem(38, 36) + val id2 = meta.addItem(63, 8) instrumenter.assertNodeExists(id1, "Cons 5 6") instrumenter.assertNodeExists(id2, "Cons 5 6") @@ -83,7 +83,7 @@ class ExpressionIdTest extends InterpreterTest { withIdsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |main = | x = Cons 1 2 @@ -101,10 +101,10 @@ class ExpressionIdTest extends InterpreterTest { | foo x + foo y |""".stripMargin val meta = new Metadata - val id1 = meta.addItem(115, 109) - val id2 = meta.addItem(161, 7) - val id3 = meta.addItem(181, 9) - val id4 = meta.addItem(218, 5) + val id1 = meta.addItem(121, 109) + val id2 = meta.addItem(167, 7) + val id3 = meta.addItem(187, 9) + val id4 = meta.addItem(224, 5) instrumenter.assertNodeExists(id1, "9") instrumenter.assertNodeExists(id2, "3") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala index acbfd0fcf730..70e054c505e0 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala @@ -52,7 +52,7 @@ class GroupingTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | fn = x -> case x of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala index 018d391b72cb..349f5f960aff 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala @@ -66,7 +66,7 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work with case expressions" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | f = case _ of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index a51c5da14b34..31f410d5b79f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -75,7 +75,7 @@ class LambdaTest extends InterpreterTest { "be able to return atoms that are evaluated with oversaturated args" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | f = x -> Cons diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 37b7058632de..3b1558819e73 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala @@ -101,7 +101,7 @@ class MethodsTest extends InterpreterTest { "be dispatched to the proper constructor" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Nil.sum = acc -> acc |Cons.sum = acc -> case this of @@ -152,7 +152,7 @@ class MethodsTest extends InterpreterTest { "work as expected when defined across different constructors" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Nil.sum = 0 |Cons.sum = case this of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala index 2677d509e93b..1b165b2147cb 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala @@ -16,14 +16,14 @@ class PatternMatchTest extends InterpreterTest { "work for simple patterns" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = | f = case _ of - | Builtins.Cons a _ -> a - | Builtins.Nil -> -10 + | Cons a _ -> a + | Nil -> -10 | - | f (Builtins.Cons 10 Builtins.Nil) - f Nil + | f (Cons 10 Nil) - f Nil |""".stripMargin eval(code) shouldEqual 20 @@ -31,7 +31,7 @@ class PatternMatchTest extends InterpreterTest { "work for anonymous catch-all patterns" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |type MyAtom a | @@ -77,7 +77,7 @@ class PatternMatchTest extends InterpreterTest { "work for level one nested patterns" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |type MyAtom | @@ -94,7 +94,7 @@ class PatternMatchTest extends InterpreterTest { "work for deeply nested patterns" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |type MyAtom | @@ -118,7 +118,7 @@ class PatternMatchTest extends InterpreterTest { "correctly result in errors for incomplete matches" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |type MyAtom | @@ -135,7 +135,7 @@ class PatternMatchTest extends InterpreterTest { "work for pattern matches in pattern matches" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |type MyAtom a |type One a diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index af8cfad6d5bf..183ec8aafeba 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -65,6 +65,7 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.List import Nil | |run = | matcher = x -> case x of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index f88fdfcaad19..355320e88d07 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -106,6 +106,7 @@ class TextTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |from Standard.Base.Data.List import Cons | |main = | IO.println (Cons Nothing Nothing).to_display_text From d771a7fec084fdfa6517092194b8e968d062dcbd Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 13 Apr 2022 12:22:04 +0200 Subject: [PATCH 18/73] WIP: remove hardcoded builtin types in Builtins Use @BuiltinType to mark specific types as BuiltinTypes, and gather necessary metadata for initializing them during Builtins setup. This is WIP, lacks documentation and such, but illustrates steps towards system of builtin objects without hardcoding everything. --- .../node/expression/builtin/Any.java | 12 ++ .../node/expression/builtin/Cons.java | 13 +++ .../node/expression/builtin/Nil.java | 12 ++ .../node/expression/builtin/Polyglot.java | 13 +++ .../node/expression/builtin/bool/Boolean.java | 12 ++ .../node/expression/builtin/bool/False.java | 12 ++ .../node/expression/builtin/bool/True.java | 12 ++ .../expression/builtin/mutable/Array.java | 13 +++ .../node/expression/builtin/mutable/Ref.java | 12 ++ .../interpreter/runtime/builtin/Builtins.java | 108 +++++++++--------- ...iltinAtomConstructor.java => Builtin.java} | 13 +-- .../runtime/scope/ModuleScope.java | 8 +- .../org/enso/interpreter/dsl/BuiltinType.java | 18 +++ .../dsl/BuiltinsMetadataProcessor.java | 50 +++----- .../enso/interpreter/dsl/MethodProcessor.java | 31 ++++- .../enso/interpreter/dsl/TypeProcessor.java | 94 +++++++++++++++ .../dsl/model/MethodDefinition.java | 2 +- 17 files changed, 331 insertions(+), 104 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java rename engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/{BuiltinAtomConstructor.java => Builtin.java} (68%) create mode 100644 lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java create mode 100644 lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java new file mode 100644 index 000000000000..d3bcccac457e --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Any extends Builtin { + public Any(ModuleScope definitionScope) { + super("Any", definitionScope); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java new file mode 100644 index 000000000000..230df4b47494 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params="head,tail") +public class Cons extends Builtin { + public Cons(ModuleScope definitionScope) { + super("Cons", definitionScope); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java new file mode 100644 index 000000000000..1d475aae618b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Nil extends Builtin { + public Nil(ModuleScope definitionScope) { + super("Nil", definitionScope); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java new file mode 100644 index 000000000000..1caea58d4b05 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Polyglot extends Builtin { + public Polyglot(ModuleScope definitionScope) { + super("Polyglot", definitionScope); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java new file mode 100644 index 000000000000..7ea678183288 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Boolean extends Builtin { + public Boolean(ModuleScope definitionScope) { + super("Boolean", definitionScope); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java new file mode 100644 index 000000000000..f5d4982a25d6 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class False extends Builtin { + public False(ModuleScope definitionScope) { + super("False", definitionScope); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java new file mode 100644 index 000000000000..dd30d094a0df --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class True extends Builtin { + public True(ModuleScope definitionScope) { + super("True", definitionScope); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java new file mode 100644 index 000000000000..e09e205dacc4 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Array extends Builtin { + public Array(ModuleScope definitionScope) { + super("Array", definitionScope); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java new file mode 100644 index 000000000000..8cf3a1b96a63 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Ref extends Builtin { + public Ref(ModuleScope definitionScope) { + super("Ref", definitionScope); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index d63f37221fe0..674efbb6677c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -16,6 +16,7 @@ import org.enso.compiler.exception.CompilerError; import org.enso.compiler.phase.BuiltinsIrBuilder; import org.enso.interpreter.Language; +import org.enso.interpreter.dsl.TypeProcessor; import org.enso.interpreter.dsl.model.MethodDefinition; import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; @@ -45,7 +46,7 @@ import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.atom.BuiltinAtomConstructor; +import org.enso.interpreter.runtime.callable.atom.Builtin; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.Constants; @@ -68,7 +69,7 @@ public static class Debug { private HashMap>> builtinNodes; // TODO Consider dropping the map and just assigning to a single variable since builtin types // should be unique - private HashMap builtinTypes; + private HashMap builtinTypes; private final AtomConstructor debug; private final AtomConstructor projectDescription; @@ -88,31 +89,6 @@ public static class Debug { private final Text text; private final Special special; - private class BuiltinTypeConstr { - private String tpeName; - private String[] paramNames; - - BuiltinTypeConstr(String tpeName) { - this.tpeName = tpeName; - this.paramNames = new String[0]; - } - - BuiltinTypeConstr(String tpeName, String... args) { - this.tpeName = tpeName; - this.paramNames = args; - } - - - public String getTpeName() { - return tpeName; - } - - public String[] getParamNames() { - return paramNames; - } - - } - /** * Creates an instance with builtin methods installed. * @@ -208,36 +184,16 @@ public Builtins(Context context) { scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); readBuiltinsMetadata(scope); + assignMethodsToBuiltins(readBuiltinTypesMetadata(scope), scope, language); + } - // FIXME: should be possible to get rid of hardcoded list of builtin types once we have all of them - // stored in metadata files - List builtinConstructors = new ArrayList<>(); - builtinConstructors.add(new BuiltinTypeConstr("Polyglot")); - builtinConstructors.add(new BuiltinTypeConstr("Ref")); - builtinConstructors.add(new BuiltinTypeConstr("Array")); - builtinConstructors.add(new BuiltinTypeConstr("Any")); - builtinConstructors.add(new BuiltinTypeConstr("Boolean")); - builtinConstructors.add(new BuiltinTypeConstr("True")); - builtinConstructors.add(new BuiltinTypeConstr("False")); - builtinConstructors.add(new BuiltinTypeConstr("Cons", "head", "tail")); - builtinConstructors.add(new BuiltinTypeConstr("Nil")); - initBuiltinTypes(builtinConstructors, scope, language); - } - - public void initBuiltinTypes(List constrs, ModuleScope scope, Language language) { - for (BuiltinTypeConstr constr: constrs) { - BuiltinAtomConstructor atom = new BuiltinAtomConstructor(constr.getTpeName(), scope); - ArgumentDefinition[] args = new ArgumentDefinition[constr.getParamNames().length]; - String[] paramNames = constr.getParamNames(); - for (int i=0; i> methods = builtinNodes.get(constr.getTpeName()); + public void assignMethodsToBuiltins(List builtins, ModuleScope scope, Language language) { + for (Builtin atom: builtins) { + String tpeName = atom.getName(); + builtinTypes.put(tpeName, atom); + Map> methods = builtinNodes.get(tpeName); if (methods != null) { - BuiltinAtomConstructor finalAtom = atom; + Builtin finalAtom = atom; methods.forEach((methodName, clazz) -> { Optional fun; try { @@ -290,6 +246,46 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } } + private List readBuiltinTypesMetadata(ModuleScope scope) { + ClassLoader classLoader = getClass().getClassLoader(); + List lines; + try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { + lines = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); + } catch (Exception ioe) { + lines = new ArrayList<>(); + ioe.printStackTrace(); + } + + return lines.stream().map(line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length < 2 || builtinMeta.length > 3) { + throw new CompilerError("Invalid builtin metadata in: " + line + " " + builtinMeta.length); + } + + String fullName = builtinMeta[1]; + Builtin builtin = null; + try { + Class clazz = (Class) Class.forName(fullName); + builtin = clazz.getDeclaredConstructor(ModuleScope.class).newInstance(scope); + if (builtinMeta.length == 2) { + builtin = builtin.initializeFields(); + } else { + // there are some type params + String[] paramNames = builtinMeta[2].split(","); + ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; + for (int i = 0; i < paramNames.length; i++) { + args[i] = new ArgumentDefinition(i, paramNames[i], ArgumentDefinition.ExecutionMode.EXECUTE); + } + builtin = builtin.initializeFields(args); + } + } catch (Exception e) { + e.printStackTrace(); + } + return builtin; + }).filter(b -> b != null).collect(Collectors.toList()); + } + + private void readBuiltinsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; @@ -353,7 +349,7 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } - public BuiltinAtomConstructor getBuiltinType(String name) { + public Builtin getBuiltinType(String name) { return builtinTypes.get(name); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java similarity index 68% rename from engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java rename to engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java index ea4e508241d6..0accf7e089bc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/BuiltinAtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java @@ -1,24 +1,21 @@ package org.enso.interpreter.runtime.callable.atom; -import com.oracle.truffle.api.interop.InteropLibrary; -import com.oracle.truffle.api.library.ExportLibrary; import org.enso.compiler.exception.CompilerError; import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.scope.ModuleScope; /** A representation of an Atom constructor for BuiltinType. */ -public class BuiltinAtomConstructor extends AtomConstructor { +public class Builtin extends AtomConstructor { private ModuleScope shadowDefinitions; /** * Creates a new Atom constructor for a given name for a BuiltinType. The constructor is not valid until {@link - * BuiltinAtomConstructor#initializeFields(ArgumentDefinition...)} is called. + * Builtin#initializeFields(ArgumentDefinition...)} is called. * * @param name the name of the Atom constructor * @param definitionScope the scope in which this constructor was defined (builtin scope) */ - public BuiltinAtomConstructor(String name, ModuleScope definitionScope) { + public Builtin(String name, ModuleScope definitionScope) { super(name, definitionScope); } @@ -37,7 +34,7 @@ public ModuleScope getShadowDefinitions() { return this.shadowDefinitions; } - public BuiltinAtomConstructor initializeFields(ArgumentDefinition... args) { - return (BuiltinAtomConstructor)super.initializeFields(args); + public Builtin initializeFields(ArgumentDefinition... args) { + return (Builtin)super.initializeFields(args); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 2ac93d0a7714..baa7a1c15414 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -1,15 +1,13 @@ package org.enso.interpreter.runtime.scope; -import com.google.common.base.Joiner; import com.oracle.truffle.api.CompilerDirectives; import java.util.*; import com.oracle.truffle.api.interop.TruffleObject; import org.enso.interpreter.runtime.Module; -import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.atom.BuiltinAtomConstructor; +import org.enso.interpreter.runtime.callable.atom.Builtin; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.error.RedefinedMethodException; import org.enso.interpreter.runtime.error.RedefinedConversionException; @@ -204,10 +202,10 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { return definedHere; } - if (atom instanceof BuiltinAtomConstructor) { + if (atom instanceof Builtin) { // Unfortunately locally defined extensions get associated with the module rather than a type within a module // BindingsMap would need to be enhanced to resolve to the constructor rather than a module - ModuleScope shadowDefinitions = ((BuiltinAtomConstructor) atom).getShadowDefinitions(); + ModuleScope shadowDefinitions = ((Builtin) atom).getShadowDefinitions(); if (shadowDefinitions != null) { AtomConstructor moduleTypeInStdLib = shadowDefinitions.associatedType; definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java new file mode 100644 index 000000000000..d6be2ffb0f83 --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -0,0 +1,18 @@ +package org.enso.interpreter.dsl; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** An annotation denoting a node that should be wrapped for standard library export. */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.SOURCE) +public @interface BuiltinType { + /** + * Comma-separated list of parameters of builting type + * @return list of params + */ + // FIXME: + String params() default ""; +} diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index 3c446aebd046..017c321599e1 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -1,21 +1,22 @@ package org.enso.interpreter.dsl; -import org.enso.interpreter.dsl.model.MethodDefinition; - import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.Filer; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.StandardLocation; import java.io.IOException; import java.io.Writer; -import java.util.HashMap; -import java.util.Map; import java.util.Set; public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { - private final Map> builtinMethods = new HashMap<>(); + + + protected abstract String metadataPath(); + + protected abstract void cleanup(); + + protected abstract void storeMetadata(Writer writer) throws IOException; @Override public final boolean process(Set annotations, RoundEnvironment roundEnv) { @@ -24,11 +25,20 @@ public final boolean process(Set annotations, RoundEnviro } if (roundEnv.processingOver()) { try { - storeBuiltinMetadata(MethodDefinition.META_PATH); + FileObject res = processingEnv.getFiler().createResource( + StandardLocation.CLASS_OUTPUT, "", + metadataPath() + ); + Writer writer = res.openWriter(); + try { + storeMetadata(writer); + } finally { + writer.close(); + } } catch (IOException e) { e.printStackTrace(); } - builtinMethods.clear(); + cleanup(); return true; } else { return handleProcess(annotations, roundEnv); @@ -45,28 +55,4 @@ public final boolean process(Set annotations, RoundEnviro */ protected abstract boolean handleProcess(Set annotations, RoundEnvironment roundEnv); - private void storeBuiltinMetadata(String path) throws IOException { - FileObject res = processingEnv.getFiler().createResource( - StandardLocation.CLASS_OUTPUT, "", - path - ); - Writer writer = res.openWriter(); - try { - for (Filer f: builtinMethods.keySet()) { - for (Map.Entry entry : builtinMethods.get(f).entrySet()) { - writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); - } - } - } finally { - writer.close(); - } - } - protected void registerBuiltinMethod(Filer f, String name, String clazzName) { - Map methods = builtinMethods.get(f); - if (methods == null) { - methods = new HashMap<>(); - builtinMethods.put(f, methods); - } - methods.put(name, clazzName); - } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index cce1ab116a97..3d216d0d5343 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -11,10 +11,9 @@ import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; -import javax.tools.FileObject; -import javax.tools.StandardLocation; import java.io.IOException; import java.io.PrintWriter; +import java.io.Writer; import java.util.*; import java.util.stream.Collectors; @@ -24,6 +23,8 @@ @AutoService(Processor.class) public class MethodProcessor extends BuiltinsMetadataProcessor { + private final Map> builtinMethods = new HashMap<>(); + /** * Processes annotated elements, generating code for each of them. * @@ -79,6 +80,14 @@ public boolean handleProcess(Set annotations, RoundEnviro return true; } + protected void storeMetadata(Writer writer) throws IOException { + for (Filer f: builtinMethods.keySet()) { + for (Map.Entry entry : builtinMethods.get(f).entrySet()) { + writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); + } + } + } + private final List necessaryImports = Arrays.asList( "com.oracle.truffle.api.frame.VirtualFrame", @@ -400,6 +409,24 @@ private boolean generateWarningsCheck( } } + protected void registerBuiltinMethod(Filer f, String name, String clazzName) { + Map methods = builtinMethods.get(f); + if (methods == null) { + methods = new HashMap<>(); + builtinMethods.put(f, methods); + } + methods.put(name, clazzName); + } + + @Override + protected String metadataPath() { + return MethodDefinition.META_PATH; + } + + protected void cleanup() { + builtinMethods.clear(); + } + private String warningCheck(MethodDefinition.ArgumentDefinition arg) { return "(" + mkArgumentInternalVarName(arg) + " instanceof WithWarnings)"; } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java new file mode 100644 index 000000000000..6f1a4e0fdce7 --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -0,0 +1,94 @@ +package org.enso.interpreter.dsl; + +import com.google.auto.service.AutoService; + +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import java.io.IOException; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +@SupportedAnnotationTypes("org.enso.interpreter.dsl.BuiltinType") +@SupportedSourceVersion(SourceVersion.RELEASE_11) +@AutoService(Processor.class) +public class TypeProcessor extends BuiltinsMetadataProcessor { + private final Map> builtinTypes = new HashMap<>(); + + private class BuiltinTypeConstr { + private String tpeName; + private String paramNames; + + BuiltinTypeConstr(String tpeName) { + this.tpeName = tpeName; + this.paramNames = ""; + } + + BuiltinTypeConstr(String tpeName, String params) { + this.tpeName = tpeName; + this.paramNames = params; + } + + + public String getTpeName() { + return tpeName; + } + + public String getParamNames() { + return paramNames; + } + + } + + + public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; + public static final String META_PATH = + "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinTypes.metadata"; + @Override + protected String metadataPath() { + return META_PATH; + } + + @Override + protected void cleanup() { + builtinTypes.clear(); + } + + @Override + protected void storeMetadata(Writer writer) throws IOException { + for (Filer f: builtinTypes.keySet()) { + for (Map.Entry entry : builtinTypes.get(f).entrySet()) { + BuiltinTypeConstr constr = entry.getValue(); + writer.append(entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); + } + } + } + + @Override + protected boolean handleProcess(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + for (Element elt : annotatedElements) { + TypeElement element = (TypeElement) elt; + BuiltinType builtinTypeAnnotation = element.getAnnotation(BuiltinType.class); + String pkgName = + processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); + String clazzName = element.getSimpleName().toString(); + registerBuiltinType(processingEnv.getFiler(), clazzName, pkgName + "." + clazzName, builtinTypeAnnotation.params()); + } + } + return true; + } + + protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { + Map methods = builtinTypes.get(f); + if (methods == null) { + methods = new HashMap<>(); + builtinTypes.put(f, methods); + } + methods.put(name, new BuiltinTypeConstr(clazzName, params)); + } +} diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index 6d11f7581d42..3541384d0897 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -14,7 +14,7 @@ public class MethodDefinition { private static final String STATEFUL = "org.enso.interpreter.runtime.state.Stateful"; public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; public static final String META_PATH = - "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/Builtins.metadata"; + "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinMethods.metadata"; private final String packageName; private final String originalClassName; From d529ad8017d034b14211c1749e2b339ab8735fc8 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 13 Apr 2022 17:24:22 +0200 Subject: [PATCH 19/73] Workaround separate compilation problems In separate compilation annotation processor will only process files that were touched. However, since we now create metadata files with bulk information and it is not possible to append/modify exisiting resource files, it will simply overwrite the original resource with a fraction of the original information. This would in turn lead to runtime issues. The only solution was to clean and compile from scratch which is not really acceptable in regular dev. Alternatively, in the past we were creating metadata file per source file. The latter however meant that during Builtins initialization we had to do a bit of File traversing. Instead we will read the previous resource file before overriding it, update entries that changed and append the past contents. It doesn't deal with all cases (renaming/delete) but neither would the alternatives. --- .../dsl/BuiltinsMetadataProcessor.java | 39 ++++++++++++++++--- .../enso/interpreter/dsl/MethodProcessor.java | 5 ++- .../enso/interpreter/dsl/TypeProcessor.java | 11 ++---- 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index 017c321599e1..87e19d50456f 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -2,21 +2,23 @@ import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.StandardLocation; -import java.io.IOException; -import java.io.Writer; -import java.util.Set; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { - protected abstract String metadataPath(); protected abstract void cleanup(); - protected abstract void storeMetadata(Writer writer) throws IOException; + protected abstract void storeMetadata(Writer writer, Map pastEntries) throws IOException; @Override public final boolean process(Set annotations, RoundEnvironment roundEnv) { @@ -24,6 +26,27 @@ public final boolean process(Set annotations, RoundEnviro return false; } if (roundEnv.processingOver()) { + // A hack to improve support for separate compilation. + // Since one cannot open the existing resource file in Append mode, + // we read the whole file and provide to the function that does the update. + // Deletes/renaming is still not gonna work but that would be the same case + // if we were writing metadata information per source file anyway. + Map pastEntries; + try { + FileObject existingFile = processingEnv.getFiler().getResource( + StandardLocation.CLASS_OUTPUT, "", + metadataPath()); + try (InputStream resource = existingFile.openInputStream()) { + pastEntries = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)). + lines(). + collect(Collectors.toMap(l -> l.split(":")[0], Function.identity())); + } + } catch (FileNotFoundException notFoundException) { + pastEntries = new HashMap<>(); + } catch (Exception e) { + e.printStackTrace(); + pastEntries = new HashMap<>(); + } try { FileObject res = processingEnv.getFiler().createResource( StandardLocation.CLASS_OUTPUT, "", @@ -31,7 +54,11 @@ public final boolean process(Set annotations, RoundEnviro ); Writer writer = res.openWriter(); try { - storeMetadata(writer); + storeMetadata(writer, pastEntries); + // Separate compilation hack + for (String value: pastEntries.values()) { + writer.append(value + "\n"); + } } finally { writer.close(); } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index 3d216d0d5343..8f85301dedab 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -80,10 +80,13 @@ public boolean handleProcess(Set annotations, RoundEnviro return true; } - protected void storeMetadata(Writer writer) throws IOException { + protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { for (Filer f: builtinMethods.keySet()) { for (Map.Entry entry : builtinMethods.get(f).entrySet()) { writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); + } } } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 6f1a4e0fdce7..fc2f86d6697b 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -22,17 +22,11 @@ private class BuiltinTypeConstr { private String tpeName; private String paramNames; - BuiltinTypeConstr(String tpeName) { - this.tpeName = tpeName; - this.paramNames = ""; - } - BuiltinTypeConstr(String tpeName, String params) { this.tpeName = tpeName; this.paramNames = params; } - public String getTpeName() { return tpeName; } @@ -58,11 +52,14 @@ protected void cleanup() { } @Override - protected void storeMetadata(Writer writer) throws IOException { + protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { for (Filer f: builtinTypes.keySet()) { for (Map.Entry entry : builtinTypes.get(f).entrySet()) { BuiltinTypeConstr constr = entry.getValue(); writer.append(entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); + } } } } From 3cfdedd64ab51ca82cef497fb60afbc419c53ebd Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 14 Apr 2022 12:12:18 +0200 Subject: [PATCH 20/73] Address PR review Main points: - get rid of additional Builtin class extending AtomConstructor and move some of the builtin info to the latter - make it possible to redefine the scope of builtin AtomConstructors Minor cleanups otherwise, all tests continue to pass with those changes. --- .../node/expression/builtin/Any.java | 6 +-- .../node/expression/builtin/Boolean.java | 16 ++++++++ .../node/expression/builtin/Cons.java | 6 +-- .../node/expression/builtin/Nil.java | 6 +-- .../node/expression/builtin/Polyglot.java | 6 +-- .../node/expression/builtin/bool/Boolean.java | 12 ------ .../node/expression/builtin/bool/False.java | 8 ++-- .../node/expression/builtin/bool/True.java | 8 ++-- .../expression/builtin/mutable/Array.java | 8 ++-- .../node/expression/builtin/mutable/Ref.java | 8 ++-- .../interpreter/runtime/builtin/Builtins.java | 18 ++++----- .../callable/atom/AtomConstructor.java | 21 +++++++++- .../runtime/callable/atom/Builtin.java | 40 ------------------- .../runtime/scope/ModuleScope.java | 20 +++++----- .../dsl/BuiltinsMetadataProcessor.java | 3 +- 15 files changed, 82 insertions(+), 104 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java index d3bcccac457e..27d6cecb37e1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -1,12 +1,12 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Any extends Builtin { +public class Any extends AtomConstructor { public Any(ModuleScope definitionScope) { - super("Any", definitionScope); + super("Any", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java new file mode 100644 index 000000000000..ac38749fd4dc --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -0,0 +1,16 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +// Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` package along with True and False +// because it currently breaks a lot of code generation for builtin methods. +// The name Boolean would clash with java.lang.Boolean. +// Before moving this definition to the `bool` package, as we should, one would have to address that problem first. +@BuiltinType +public class Boolean extends AtomConstructor { + public Boolean(ModuleScope definitionScope) { + super("Boolean", definitionScope, true); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java index 230df4b47494..2c9404ca7929 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java @@ -1,13 +1,13 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType(params="head,tail") -public class Cons extends Builtin { +public class Cons extends AtomConstructor { public Cons(ModuleScope definitionScope) { - super("Cons", definitionScope); + super("Cons", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java index 1d475aae618b..7483946ea2cd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java @@ -1,12 +1,12 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Nil extends Builtin { +public class Nil extends AtomConstructor { public Nil(ModuleScope definitionScope) { - super("Nil", definitionScope); + super("Nil", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java index 1caea58d4b05..6d5142244bd0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java @@ -1,13 +1,13 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Polyglot extends Builtin { +public class Polyglot extends AtomConstructor { public Polyglot(ModuleScope definitionScope) { - super("Polyglot", definitionScope); + super("Polyglot", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java deleted file mode 100644 index 7ea678183288..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/Boolean.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.enso.interpreter.node.expression.builtin; - -import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; -import org.enso.interpreter.runtime.scope.ModuleScope; - -@BuiltinType -public class Boolean extends Builtin { - public Boolean(ModuleScope definitionScope) { - super("Boolean", definitionScope); - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java index f5d4982a25d6..7385f68aa1c9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java @@ -1,12 +1,12 @@ -package org.enso.interpreter.node.expression.builtin; +package org.enso.interpreter.node.expression.builtin.bool; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class False extends Builtin { +public class False extends AtomConstructor { public False(ModuleScope definitionScope) { - super("False", definitionScope); + super("False", definitionScope, true); } } \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java index dd30d094a0df..ce808a6a9ec3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java @@ -1,12 +1,12 @@ -package org.enso.interpreter.node.expression.builtin; +package org.enso.interpreter.node.expression.builtin.bool; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class True extends Builtin { +public class True extends AtomConstructor { public True(ModuleScope definitionScope) { - super("True", definitionScope); + super("True", definitionScope, true); } } \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java index e09e205dacc4..b522e51e48ff 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java @@ -1,13 +1,13 @@ -package org.enso.interpreter.node.expression.builtin; +package org.enso.interpreter.node.expression.builtin.mutable; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Array extends Builtin { +public class Array extends AtomConstructor { public Array(ModuleScope definitionScope) { - super("Array", definitionScope); + super("Array", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java index 8cf3a1b96a63..4cdf59490bb3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java @@ -1,12 +1,12 @@ -package org.enso.interpreter.node.expression.builtin; +package org.enso.interpreter.node.expression.builtin.mutable; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.Builtin; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Ref extends Builtin { +public class Ref extends AtomConstructor { public Ref(ModuleScope definitionScope) { - super("Ref", definitionScope); + super("Ref", definitionScope, true); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 674efbb6677c..7593693744b7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -46,7 +46,6 @@ import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.atom.Builtin; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.Constants; @@ -69,7 +68,7 @@ public static class Debug { private HashMap>> builtinNodes; // TODO Consider dropping the map and just assigning to a single variable since builtin types // should be unique - private HashMap builtinTypes; + private HashMap builtinTypes; private final AtomConstructor debug; private final AtomConstructor projectDescription; @@ -187,13 +186,12 @@ public Builtins(Context context) { assignMethodsToBuiltins(readBuiltinTypesMetadata(scope), scope, language); } - public void assignMethodsToBuiltins(List builtins, ModuleScope scope, Language language) { - for (Builtin atom: builtins) { + public void assignMethodsToBuiltins(List builtins, ModuleScope scope, Language language) { + for (AtomConstructor atom: builtins) { String tpeName = atom.getName(); builtinTypes.put(tpeName, atom); Map> methods = builtinNodes.get(tpeName); if (methods != null) { - Builtin finalAtom = atom; methods.forEach((methodName, clazz) -> { Optional fun; try { @@ -203,7 +201,7 @@ public void assignMethodsToBuiltins(List builtins, ModuleScope scope, L e.printStackTrace(); fun = Optional.empty(); } - fun.ifPresent(f -> scope.registerMethod(finalAtom, methodName, f)); + fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); }); } } @@ -246,7 +244,7 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } } - private List readBuiltinTypesMetadata(ModuleScope scope) { + private List readBuiltinTypesMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { @@ -263,9 +261,9 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { } String fullName = builtinMeta[1]; - Builtin builtin = null; + AtomConstructor builtin = null; try { - Class clazz = (Class) Class.forName(fullName); + Class clazz = (Class) Class.forName(fullName); builtin = clazz.getDeclaredConstructor(ModuleScope.class).newInstance(scope); if (builtinMeta.length == 2) { builtin = builtin.initializeFields(); @@ -349,7 +347,7 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } - public Builtin getBuiltinType(String name) { + public AtomConstructor getBuiltinType(String name) { return builtinTypes.get(name); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index b0b20dedfb40..3124d0d2a22c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -11,7 +11,6 @@ import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; -import org.enso.compiler.exception.CompilerError; import org.enso.interpreter.node.ClosureRootNode; import org.enso.interpreter.node.ExpressionNode; import org.enso.interpreter.node.callable.argument.ReadArgumentNode; @@ -36,7 +35,8 @@ public class AtomConstructor implements TruffleObject { private final String name; - private final ModuleScope definitionScope; + private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; + private final boolean builtin; private @CompilerDirectives.CompilationFinal Atom cachedInstance; private @CompilerDirectives.CompilationFinal Function constructorFunction; @@ -48,14 +48,31 @@ public class AtomConstructor implements TruffleObject { * @param definitionScope the scope in which this constructor was defined */ public AtomConstructor(String name, ModuleScope definitionScope) { + this(name, definitionScope, false); + } + + public AtomConstructor(String name, ModuleScope definitionScope, Boolean builtin) { this.name = name; this.definitionScope = definitionScope; + this.builtin = builtin; } public boolean isInitialized() { return constructorFunction != null; } + public boolean isBuiltin() { + return builtin; + } + + public void setShadowDefinitions(ModuleScope scope) { + if (builtin) { + this.definitionScope = scope; + } else { + throw new RuntimeException("Attempting to modify scope of a non-builtin type post-construction is not allowed"); + } + } + /** * Generates a constructor function for this {@link AtomConstructor}. * Note that such manually constructed argument definitions must not have default arguments. diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java deleted file mode 100644 index 0accf7e089bc..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Builtin.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.enso.interpreter.runtime.callable.atom; - -import org.enso.compiler.exception.CompilerError; -import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** A representation of an Atom constructor for BuiltinType. */ -public class Builtin extends AtomConstructor { - - private ModuleScope shadowDefinitions; - /** - * Creates a new Atom constructor for a given name for a BuiltinType. The constructor is not valid until {@link - * Builtin#initializeFields(ArgumentDefinition...)} is called. - * - * @param name the name of the Atom constructor - * @param definitionScope the scope in which this constructor was defined (builtin scope) - */ - public Builtin(String name, ModuleScope definitionScope) { - super(name, definitionScope); - } - - /** - * Additional scope for BuiltinTypes pointing to an auxiliary scope in standard library - * @param scope the scope of definitions in standard library - */ - public void setShadowDefinitions(ModuleScope scope) { - if (shadowDefinitions != null) { - throw new CompilerError("cannot set shadow definitions twice"); - } - this.shadowDefinitions = scope; - } - - public ModuleScope getShadowDefinitions() { - return this.shadowDefinitions; - } - - public Builtin initializeFields(ArgumentDefinition... args) { - return (Builtin)super.initializeFields(args); - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index baa7a1c15414..41a20129a655 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -7,7 +7,6 @@ import com.oracle.truffle.api.interop.TruffleObject; import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.atom.Builtin; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.error.RedefinedMethodException; import org.enso.interpreter.runtime.error.RedefinedConversionException; @@ -202,16 +201,15 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { return definedHere; } - if (atom instanceof Builtin) { - // Unfortunately locally defined extensions get associated with the module rather than a type within a module - // BindingsMap would need to be enhanced to resolve to the constructor rather than a module - ModuleScope shadowDefinitions = ((Builtin) atom).getShadowDefinitions(); - if (shadowDefinitions != null) { - AtomConstructor moduleTypeInStdLib = shadowDefinitions.associatedType; - definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); - if (definedHere != null) { - return definedHere; - } + if (atom.isBuiltin()) { + // Unfortunately locally defined extensions get associated with the module rather than a type + // within a module. + // BindingsMap would need to be enhanced to resolve to the constructor rather than a module but + // that will likely break some use-cases as it could become ambiguous. + AtomConstructor moduleTypeInStdLib = atom.getDefinitionScope().associatedType; + definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); + if (definedHere != null) { + return definedHere; } } return imports.stream() diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index 87e19d50456f..d4b29a53eb04 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -8,6 +8,7 @@ import javax.tools.StandardLocation; import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.NoSuchFileException; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @@ -41,7 +42,7 @@ public final boolean process(Set annotations, RoundEnviro lines(). collect(Collectors.toMap(l -> l.split(":")[0], Function.identity())); } - } catch (FileNotFoundException notFoundException) { + } catch (NoSuchFileException notFoundException) { pastEntries = new HashMap<>(); } catch (Exception e) { e.printStackTrace(); From 8ee6654bd4bed03dd6e6b8bd818284faa6dd28b7 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 14 Apr 2022 18:04:21 +0200 Subject: [PATCH 21/73] CamelCase to Snake_Case for builtin types --- .../src/main/java/org/enso/interpreter/dsl/TypeProcessor.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index fc2f86d6697b..542bd163a312 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -74,7 +74,9 @@ protected boolean handleProcess(Set annotations, RoundEnv String pkgName = processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); String clazzName = element.getSimpleName().toString(); - registerBuiltinType(processingEnv.getFiler(), clazzName, pkgName + "." + clazzName, builtinTypeAnnotation.params()); + // Replace CamelCase class name to Snake_Case used in Enso + String ensoTypeName = clazzName.replaceAll("([^_A-Z])([A-Z])", "$1_$2"); + registerBuiltinType(processingEnv.getFiler(), ensoTypeName, pkgName + "." + clazzName, builtinTypeAnnotation.params()); } } return true; From c04f11ee85369ebdd858dbe7d85046604b2a1cd3 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 15 Apr 2022 16:43:01 +0200 Subject: [PATCH 22/73] Move DataflowError to stdlib --- .../Base/0.0.0-dev/src/Data/List.enso | 3 +- .../Base/0.0.0-dev/src/Error/Common.enso | 149 ++++++++++++++++++ .../Base/0.0.0-dev/src/Error/Extensions.enso | 92 ----------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../callable/resolver/BaseResolverNode.java | 2 +- .../node/expression/builtin/Error.java | 12 ++ .../interpreter/runtime/builtin/Builtins.java | 8 +- .../runtime/error/DataflowError.java | 2 +- .../interpreter/runtime/type/Constants.java | 4 +- .../error/FailedToApplyEditsException.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 55 ------- .../test/instrument/RuntimeErrorsTest.scala | 100 +++++++----- .../RuntimeVisualisationsTest.scala | 19 ++- .../test/semantic/DataflowErrorsTest.scala | 11 +- 14 files changed, 256 insertions(+), 205 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 59a7970cfeff..6fbe8c908a12 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,5 +1,5 @@ from Standard.Builtins import all -from Standard.Builtins export Nil, Cons +from Standard.Base.Error.Common import Error from Standard.Base.Data.Boolean import True, False ## The basic cons-list type. @@ -377,4 +377,3 @@ map_helper list cons f = case list of Unsafe.set_atom_field cons 1 res @Tail_Call here.map_helper t res f Nil -> Unsafe.set_atom_field cons 1 Nil - diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 02dee47260dd..ea659dff0a29 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -1,4 +1,153 @@ from Standard.Base import all +import Standard.Base.Data.Json + +## Dataflow errors. +type Error + + ## A type representing dataflow errors. + + A dataflow error in Enso is one that behaves like a standard value, and + hence represents erroneous states in a way that exists _within_ standard + control flow. + + ? Dataflow Errors or Panics + Whilst a Panic is useful for unrecoverable situations, most Enso APIs + are designed to use dataflow errors instead. As they exist within the + normal program control flow, they are able to be represented on the + Enso graph. + @Builtin_Type + type Error + + ## Creates a new dataflow error containing the provided payload. + + Arguments: + - payload: The contents of the dataflow error to be created. + + > Example + Throw a dataflow error containing the text "Oops". + + Error.throw "Oops" + throw : Any -> Error + throw payload = @Builtin_Method "Error.throw" + + ## PRIVATE + + Executes the provided handler on a dataflow error, or executes as + identity on a non-error value. + + Arguments: + - handler: The function to call on this if it is an error value. + catch_primitive : (Error -> Any) -> Any + catch_primitive handler = @Builtin_Method "Error.catch_primitive" + + ## PRIVATE + UNSTABLE + + Returns a textual representation of the stack trace attached to an error. + get_stack_trace_text : Text + get_stack_trace_text = @Builtin_Method "Error.get_stack_trace_text" + + ## Converts an error to a corresponding textual representation. + + > Example + Converting a thrown error to text. + + Error.throw "foo" . to_text + to_text : Text + to_text = @Builtin_Method "Error.to_text" + + ## UNSTABLE + + Returns a human-readable text representing this error. + to_display_text : Text + to_display_text = "Error: " + (this.catch .to_display_text) + + ## Executes the provided handler on a dataflow error, or returns a non-error + value unchanged. + + Arguments: + - handler: The function to call on this if it is an error value. By default + this is identity. + + > Example + Catching an erroneous value and getting the length of its message. + + import Standard.Examples + + example_catch = + Examples.throw_error.catch (err -> err.message.length) + catch : (Error -> Any) -> Any + catch (handler = x->x) = this.catch_primitive handler + + ## UNSTABLE + + Returns a display representation of the dataflow error on which it is called. + + > Example + Displaying a dataflow error. + + import Standard.Examples + + example_display = Examples.throw_error.to_default_visualization_data + to_default_visualization_data : Text + to_default_visualization_data = this.catch .to_default_visualization_data + + ## UNSTABLE + + Returns a JSON representation of the dataflow error. + + > Example + Converting a dataflow error to JSON. + + import Standard.Examples + + example_to_json = Examples.throw_error.to_json + to_json : Json.Object + to_json = + error_type = ["type", "Error"] + error_content = ["content", this.catch .to_json] + error_message = ["message", this.catch .to_display_text] + Json.from_pairs [error_type, error_content, error_message] + + ## Transforms an error. + + Arguments: + - f: The function used to transform the error. + + If `this` is a non-error value it is returned unchanged. However, if `this` + is an error, the error is transformed using the provided function + + > Example + Transforming an error value. + + import Standard.Examples + + example_map_error = + map = Examples.map + map.get 10 . map_error (_ -> "The element 10 was not found.") + map_error : (Error -> Error) -> Any + map_error f = this.catch (x -> Error.throw (f x)) + + ## ADVANCED + UNSTABLE + + Returns the attached stack trace of the error. + + The ordering of the resulting vector is such that the top stack frame is the + first element. + stack_trace : Vector.Vector Stack_Trace_Element + stack_trace = + Panic.get_attached_stack_trace this + + ## Checks if `this` is an error. + + > Example + Checking if the value 1 is an error. + + 1.is_error + is_error : Boolean + is_error = True + type Illegal_State_Error diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso index 2648f8cfb508..93a681c70645 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso @@ -51,78 +51,6 @@ Unimplemented_Error.to_display_text = "An implementation is missing: " + this.me unimplemented : Text -> Void unimplemented message="" = Panic.throw (Unimplemented_Error message) -## Executes the provided handler on a dataflow error, or returns a non-error - value unchanged. - - Arguments: - - handler: The function to call on this if it is an error value. By default - this is identity. - - > Example - Catching an erroneous value and getting the length of its message. - - import Standard.Examples - - example_catch = - Examples.throw_error.catch (err -> err.message.length) -Error.catch : (Error -> Any) -> Any -Error.catch (handler = x->x) = this.catch_primitive handler - -## UNSTABLE - - Returns a display representation of the dataflow error on which it is called. - - > Example - Displaying a dataflow error. - - import Standard.Examples - - example_display = Examples.throw_error.to_default_visualization_data -Error.to_default_visualization_data : Text -Error.to_default_visualization_data = this.catch .to_default_visualization_data - -## UNSTABLE - - Returns a human-readable text representing this error. -Error.to_display_text : Text -Error.to_display_text = "Error: " + (this.catch .to_display_text) - -## UNSTABLE - - Returns a JSON representation of the dataflow error. - - > Example - Converting a dataflow error to JSON. - - import Standard.Examples - - example_to_json = Examples.throw_error.to_json -Error.to_json : Json.Object -Error.to_json = - error_type = ["type", "Error"] - error_content = ["content", this.catch .to_json] - error_message = ["message", this.catch .to_display_text] - Json.from_pairs [error_type, error_content, error_message] - -## Transforms an error. - - Arguments: - - f: The function used to transform the error. - - If `this` is a non-error value it is returned unchanged. However, if `this` - is an error, the error is transformed using the provided function - - > Example - Transforming an error value. - - import Standard.Examples - - example_map_error = - map = Examples.map - map.get 10 . map_error (_ -> "The element 10 was not found.") -Error.map_error : (Error -> Error) -> Any -Error.map_error f = this.catch (x -> Error.throw (f x)) - ## ADVANCED UNSTABLE @@ -140,26 +68,6 @@ Panic.get_attached_stack_trace error = stack_with_prims = Vector.Vector prim_stack stack_with_prims.map Runtime_Extensions.wrap_primitive_stack_trace_element -## ADVANCED - UNSTABLE - - Returns the attached stack trace of the error. - - The ordering of the resulting vector is such that the top stack frame is the - first element. -Error.stack_trace : Vector.Vector Stack_Trace_Element -Error.stack_trace = - Panic.get_attached_stack_trace this - -## Checks if `this` is an error. - - > Example - Checking if the value 1 is an error. - - 1.is_error -Error.is_error : Boolean -Error.is_error = True - ## Takes any value, and if it is a dataflow error, throws it as a Panic, otherwise, returns the original value unchanged. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 8f63999427b2..8074408be1b7 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -52,7 +52,7 @@ export project.Warning from project.Data.Array export Array from project.Data.Any export all from project.Data.Boolean export all -from project.Data.List export Nil, Cons +from project.Data.List export Nil, Cons, List from project.Data.Number.Extensions export all hiding Math, String, Double from project.Data.Noise export all hiding Noise from project.Data.Pair export Pair diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java index 2dfa504a3f06..299043e730b2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java @@ -25,7 +25,7 @@ protected Function throwIfNull(Function function, Object _this, UnresolvedSymbol @CompilerDirectives.TruffleBoundary Function resolveMethodOnError(UnresolvedSymbol symbol) { - return symbol.resolveFor(getContext().getBuiltins().dataflowError().constructor()); + return symbol.resolveFor(getContext().getBuiltins().dataflowError()); } @CompilerDirectives.TruffleBoundary diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java new file mode 100644 index 000000000000..c566ac7284f6 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Error extends AtomConstructor { + public Error(ModuleScope definitionScope) { + super("Error", definitionScope, true); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 7593693744b7..ae933245f2e3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -77,7 +77,6 @@ public static class Debug { private final AtomConstructor panic; private final AtomConstructor caughtPanic; - private final DataflowError dataflowError; private final Error error; private final Module module; private final ModuleScope scope; @@ -101,7 +100,6 @@ public Builtins(Context context) { builtinTypes = new HashMap<>(); debug = new AtomConstructor("Debug", scope).initializeFields(); - dataflowError = new DataflowError(language, scope); Warning.initWarningMethods(language, scope); projectDescription = new AtomConstructor("Project_Description", scope) @@ -462,8 +460,8 @@ public Ordering ordering() { } /** @return the container for the dataflow error-related builtins */ - public DataflowError dataflowError() { - return dataflowError; + public AtomConstructor dataflowError() { + return builtinTypes.get("Error"); } public Special special() { @@ -501,7 +499,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.DECIMAL: return number.getDecimal().newInstance(); case Constants.ERROR: - return dataflowError.constructor().newInstance(); + return dataflowError().newInstance(); case Constants.FUNCTION: return function.newInstance(); case Constants.INTEGER: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/DataflowError.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/DataflowError.java index 1d93e24e176b..c7c86c2865eb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/DataflowError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/DataflowError.java @@ -116,7 +116,7 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { Context context = getContext(); - return conversion.resolveFor(target, context.getBuiltins().dataflowError().constructor()); + return conversion.resolveFor(target, context.getBuiltins().dataflowError()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 56d15144e3c9..e49bc859fad4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -4,10 +4,10 @@ public class Constants { public static final String ANY = "Standard.Base.Data.Any.Any"; - public static final String ARRAY = "Standard.Data.Main.Array"; + public static final String ARRAY = "Standard.Base.Data.Array.Array"; public static final String BOOLEAN = "Standard.Builtins.Main.Boolean"; public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; - public static final String ERROR = "Standard.Builtins.Main.Error"; + public static final String ERROR = "Standard.Base.Error.Common.Error"; public static final String FUNCTION = "Standard.Builtins.Main.Function"; public static final String INTEGER = "Standard.Builtins.Main.Integer"; public static final String MANAGED_RESOURCE = "Standard.Builtins.Main.Managed_Resource"; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/error/FailedToApplyEditsException.java b/engine/runtime/src/main/java/org/enso/interpreter/service/error/FailedToApplyEditsException.java index 9d274e494789..e6515c38c17e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/error/FailedToApplyEditsException.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/error/FailedToApplyEditsException.java @@ -18,7 +18,7 @@ public class FailedToApplyEditsException extends RuntimeException implements Ser */ public FailedToApplyEditsException(File path, Object edits, Object failure, Object source) { super( - "Filed to apply edits for file " + "Failed to apply edits for file " + new MaskedPath(path.toPath()).applyMasking() + ", edits=" + new MaskedString(edits.toString()).applyMasking() diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 1796158ca571..13d82a8bcc97 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -43,61 +43,6 @@ type Debug eval : Text -> Any eval expression = @Builtin_Method "Debug.eval" -## Dataflow errors. -type Error - - ## A type representing dataflow errors. - - A dataflow error in Enso is one that behaves like a standard value, and - hence represents erroneous states in a way that exists _within_ standard - control flow. - - ? Dataflow Errors or Panics - Whilst a Panic is useful for unrecoverable situations, most Enso APIs - are designed to use dataflow errors instead. As they exist within the - normal program control flow, they are able to be represented on the - Enso graph. - @Builtin_Type - type Error - - ## Creates a new dataflow error containing the provided payload. - - Arguments: - - payload: The contents of the dataflow error to be created. - - > Example - Throw a dataflow error containing the text "Oops". - - Error.throw "Oops" - throw : Any -> Error - throw payload = @Builtin_Method "Error.throw" - - ## PRIVATE - - Executes the provided handler on a dataflow error, or executes as - identity on a non-error value. - - Arguments: - - handler: The function to call on this if it is an error value. - catch_primitive : (Error -> Any) -> Any - catch_primitive handler = @Builtin_Method "Any.catch" - - ## PRIVATE - UNSTABLE - - Returns a textual representation of the stack trace attached to an error. - get_stack_trace_text : Text - get_stack_trace_text = @Builtin_Method "Error.get_stack_trace_text" - - ## Converts an error to a corresponding textual representation. - - > Example - Converting a thrown error to text. - - Error.throw "foo" . to_text - to_text : Text - to_text = @Builtin_Method "Error.to_text" - @Builtin_Type type Prim_Warning type Prim_Warning diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 5092e8b856c6..b47643f424f4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -102,7 +102,7 @@ class RuntimeErrorsTest } def receive: Option[Api.Response] = { - Option(messageQueue.poll(10, TimeUnit.SECONDS)) + Option(messageQueue.poll(60, TimeUnit.SECONDS)) } def receive(n: Int): List[Api.Response] = { @@ -127,6 +127,13 @@ class RuntimeErrorsTest val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + it should "return panic sentinels in method body" in { val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() @@ -292,13 +299,13 @@ class RuntimeErrorsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata // foo body id - metadata.addItem(70, 5) - val xId = metadata.addItem(84, 19) - val yId = metadata.addItem(112, 8) - val mainResId = metadata.addItem(125, 7) + metadata.addItem(79, 5) + val xId = metadata.addItem(93, 19) + val yId = metadata.addItem(121, 8) + val mainResId = metadata.addItem(134, 7) val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all | |type MyError | @@ -337,7 +344,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -356,6 +364,12 @@ class RuntimeErrorsTest ), context.executionComplete(contextId) ) + + val loadedLibraries = responses.collect { + case Api.Response(None, Api.LibraryLoaded(namespace, name, _, _)) => + (namespace, name) + } + loadedLibraries should contain(("Standard", "Base")) } it should "return panic sentinels continuing execution" in { @@ -444,12 +458,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(64, 19) - val yId = metadata.addItem(92, 2) - val mainResId = metadata.addItem(99, 12) + val xId = metadata.addItem(60, 19) + val yId = metadata.addItem(88, 2) + val mainResId = metadata.addItem(95, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError | @@ -487,7 +501,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + val responses = context.receive(7) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq ( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -518,12 +533,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(64, 19) - val yId = metadata.addItem(92, 5) - val mainResId = metadata.addItem(102, 12) + val xId = metadata.addItem(60, 19) + val yId = metadata.addItem(88, 5) + val mainResId = metadata.addItem(98, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError | @@ -561,7 +576,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -592,7 +608,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + val responses2 = context.receive(4) + responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), context.executionComplete(contextId) @@ -657,12 +674,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(79, 20) - val yId = metadata.addItem(108, 5) - val mainResId = metadata.addItem(118, 12) + val xId = metadata.addItem(75, 20) + val yId = metadata.addItem(104, 5) + val mainResId = metadata.addItem(114, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError1 |type MyError2 @@ -701,7 +718,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -743,13 +761,13 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val fooThrowId = metadata.addItem(74, 20) - val xId = metadata.addItem(111, 8) - val yId = metadata.addItem(128, 5) - val mainResId = metadata.addItem(138, 12) + val fooThrowId = metadata.addItem(70, 20) + val xId = metadata.addItem(107, 8) + val yId = metadata.addItem(124, 5) + val mainResId = metadata.addItem(134, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError1 |type MyError2 @@ -791,7 +809,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1048,12 +1067,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(79, 20) - val yId = metadata.addItem(108, 5) - val mainResId = metadata.addItem(118, 12) + val xId = metadata.addItem(75, 20) + val yId = metadata.addItem(104, 5) + val mainResId = metadata.addItem(114, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError1 |type MyError2 @@ -1092,7 +1111,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1279,12 +1299,13 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(75, 8) - val yId = metadata.addItem(92, 5) - val mainResId = metadata.addItem(102, 12) + val xId = metadata.addItem(118, 8) + val yId = metadata.addItem(135, 5) + val mainResId = metadata.addItem(145, 12) val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |foo = | Error.throw 9 @@ -1323,7 +1344,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1352,7 +1374,7 @@ class RuntimeErrorsTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 4), model.Position(3, 17)), + model.Range(model.Position(4, 4), model.Position(4, 17)), "10002 - 10000" ) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 1c45762d58fe..22a92299f5b7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -1675,10 +1675,10 @@ class RuntimeVisualisationsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(46, 14) + val idMain = metadata.addItem(42, 14) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | Error.throw 42 @@ -1707,7 +1707,9 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(3) should contain theSameElementsAs Seq( + val responses = context.receive(n = 4, timeoutSeconds = 60)) + + responses should contain allOf( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1717,6 +1719,12 @@ class RuntimeVisualisationsTest context.executionComplete(contextId) ) + val loadedLibraries = responses.collect { + case Api.Response(None, Api.LibraryLoaded(namespace, name, _, _)) => + (namespace, name) + } + loadedLibraries should contain(("Standard", "Base")) + // attach visualisation context.send( Api.Request( @@ -1863,11 +1871,12 @@ class RuntimeVisualisationsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(77, 28) + val idMain = metadata.addItem(120, 28) val code = """from Standard.Builtins import all |import Standard.Base.Data.List + |from Standard.Base.Error.Common import all | |main = | Error.throw List.Empty_Error @@ -1902,7 +1911,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) val pushContextResponses = - context.receive(n = 4, timeoutSeconds = 90) + context.receive(n = 5, timeoutSeconds = 90) pushContextResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala index cc49c3b55b36..bc252d053421 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala @@ -12,6 +12,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through pattern matches" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type MyError | @@ -30,6 +31,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through specialized pattern matches" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type MyError | @@ -48,7 +50,7 @@ class DataflowErrorsTest extends InterpreterTest { "be catchable by a user-provided special handling function" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all | |main = | intError = Error.throw 1 @@ -60,6 +62,7 @@ class DataflowErrorsTest extends InterpreterTest { "accept a constructor handler in catch function" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type MyCons err | @@ -74,6 +77,7 @@ class DataflowErrorsTest extends InterpreterTest { "accept a method handle in catch function" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type MyRecovered x |type MyError x @@ -97,6 +101,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through atom construction" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type My_Atom a |type My_Error @@ -114,6 +119,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through method resolution" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type My_Atom |type My_Error @@ -133,6 +139,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through function calls" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type My_Error | @@ -149,6 +156,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through builtin methods" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type My_Error | @@ -164,6 +172,7 @@ class DataflowErrorsTest extends InterpreterTest { "not propagate when explicitly accepted by type and by annotation" in { val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |type My_Error | From 20f8be48f91354cd1da6b8677be8dd8948f4b9d9 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 15 Apr 2022 17:15:32 +0200 Subject: [PATCH 23/73] typo --- .../interpreter/test/instrument/RuntimeVisualisationsTest.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 22a92299f5b7..c2097f008a78 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -1707,7 +1707,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val responses = context.receive(n = 4, timeoutSeconds = 60)) + val responses = context.receive(n = 4, timeoutSeconds = 60) responses should contain allOf( Api.Response(requestId, Api.PushContextResponse(contextId)), From fd094e15334de992685f7005ac2c22eb2486ea6e Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 11:07:19 +0200 Subject: [PATCH 24/73] Move all error types + text A number of re-adjustments were necessary since Error/Text types are tested extensively. Notice one additional test in DataflowErrorsTest where Syntax Error has a slightly different display text when caught. This was distilled from RuntimeServerTest, which I think had it wrong the last time but that needs to be verified. --- .../Base/0.0.0-dev/src/Data/Text/Text.enso | 40 ++ .../Base/0.0.0-dev/src/Error/Common.enso | 376 ++++++++++++++++++ .../Base/0.0.0-dev/src/Error/Extensions.enso | 170 -------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../builtin/error/ArithmeticError.java | 13 + .../expression/builtin/error/ArityError.java | 13 + .../expression/builtin/error/CaughtPanic.java | 12 + .../builtin/error/CompileError.java | 13 + .../error/InexhaustivePatternMatchError.java | 13 + .../builtin/error/InvalidArrayIndexError.java | 13 + .../error/InvalidConversionTargetError.java | 13 + .../builtin/error/ModuleDoesNotExist.java | 13 + .../error/ModuleNotInPackageError.java | 13 + .../builtin/error/NoSuchConversionError.java | 13 + .../builtin/error/NoSuchMethodError.java | 13 + .../builtin/error/NotInvokableError.java | 13 + .../node/expression/builtin/error/Panic.java | 12 + .../builtin/error/PolyglotError.java | 13 + .../expression/builtin/error/SyntaxError.java | 13 + .../expression/builtin/error/TypeError.java | 13 + .../builtin/error/UninitializedState.java | 13 + .../error/UnsupportedArgumentTypes.java | 13 + ...oSuchConversionErrorToDisplayTextNode.java | 2 +- .../builtin/text/PrimTextHelper.java | 12 + .../node/expression/builtin/text/Text.java | 12 + .../builtin/text/util/ExpectStringNode.java | 2 +- .../builtin/text/util/ExpectTextNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 43 +- .../interpreter/runtime/builtin/Error.java | 220 ++-------- .../interpreter/runtime/builtin/Text.java | 34 -- .../interpreter/runtime/data/text/Text.java | 4 +- .../interpreter/runtime/type/Constants.java | 4 +- .../runtime/src/main/resources/Builtins.enso | 223 ----------- .../enso/compiler/codegen/IrToTruffle.scala | 4 +- .../codegen/RuntimeStubsGenerator.scala | 4 + .../test/instrument/ReplTest.scala | 1 + .../test/instrument/RuntimeErrorsTest.scala | 29 +- .../test/instrument/RuntimeServerTest.scala | 42 +- .../RuntimeSuggestionUpdatesTest.scala | 17 +- .../RuntimeVisualisationsTest.scala | 14 +- .../semantic/CompileDiagnosticsTest.scala | 13 +- .../test/semantic/DataflowErrorsTest.scala | 17 + .../test/semantic/InteropTest.scala | 1 + .../test/semantic/PanicsTest.scala | 6 +- .../interpreter/test/semantic/StateTest.scala | 2 +- .../interpreter/test/semantic/TextTest.scala | 2 + test/Tests/src/Data/Noise/Generator_Spec.enso | 4 +- 47 files changed, 842 insertions(+), 694 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Text.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso new file mode 100644 index 000000000000..59ece2441502 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso @@ -0,0 +1,40 @@ +## Enso's text type. +type Text + + ## Enso's text type. + + Enso's text type is natively unicode aware, and will handle arbitrary + textual data. + + ? Concatenation + Enso's text type uses a rope-based structure under the hood to provide + users with efficient concatenation operations. + @Builtin_Type + type Text + + ## Concatenates the text that to the right side of this. + + Arguments: + - that: The text to concatenate to this. + + > Example + Concatenating two texts. + + "Hello" + ", world!" + + : Text -> Text + + that = @Builtin_Method "Text.+" + +## Internal text utilities for inspecting text primitives. +type Prim_Text_Helper + + ## PRIVATE + + A container for primitive text operations. + @Builtin_Type + type Prim_Text_Helper + + ## PRIVATE + + Forces flattening of a text value. + optimize : Text + optimize = @Builtin_Method "Prim_Text_Helpers.optimize" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index ea659dff0a29..1a080955b39c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -1,5 +1,6 @@ from Standard.Base import all import Standard.Base.Data.Json +from Standard.Base.Runtime.Extensions as Runtime_Extensions import Stack_Trace_Element ## Dataflow errors. type Error @@ -182,3 +183,378 @@ type Wrapped_Dataflow_Error payload ## PRIVATE Throws the original error. Wrapped_Dataflow_Error.unwrap = Error.throw this.payload + +type Caught_Panic + ## A wrapper for a caught panic. + + Arguments: + - payload: the payload carried by the error. + - internal_original_exception (private): the original Java exception that is + the source of this panic. Only for internal use. To get the Java exception + from polyglot exceptions, match the `payload` on `Polyglot_Error` and + extract the Java object from there. + @Builtin_Type + type Caught_Panic payload internal_original_exception + + ## Converts this caught panic into a dataflow error containing the same + payload and stack trace. + convert_to_dataflow_error : Error + convert_to_dataflow_error = @Builtin_Method "Caught_Panic.convert_to_dataflow_error" + + ## Returns the stack trace of the caught panic. + stack_trace : Vector.Vector Stack_Trace_Element + stack_trace = + Panic.get_attached_stack_trace this + +## Panics. +type Panic + + ## A panic is an error condition that is based _outside_ of the normal + program control flow. + + Panics "bubble up" through the program until they reach either an + invocation of Panic.recover Any or the program's main method. An unhandled + panic in main will terminate the program. + + ? Dataflow Errors or Panics + Panics are designed to be used for unrecoverable situations that need + to be handled through non-linear control flow mechanisms. + @Builtin_Type + type Panic + + ## Throws a new panic with the provided payload. + + Arguments: + - payload: The contents of the panic to be thrown. If the payload is a + `Caught_Panic` or a raw Java exception, instead of throwing a new panic + with it as a payload, the original exception is rethrown, preserving + its stacktrace. + + > Example + Throwing a panic containing the text "Oh no!". + + Panic.throw "Oh no!" + + > Example + Use together with `Panic.catch` to catch only specific types of errors + and rethrow any others, without affecting their stacktraces. + + Panic.catch Any (Panic.throw "foo") caught_panic-> case caught_panic.payload of + Illegal_Argument_Error message _ -> "Illegal arguments were provided: "+message + other_panic -> Panic.throw other_panic + throw : Any -> Panic + throw payload = @Builtin_Method "Panic.throw" + + ## PRIVATE + Executes the provided action and if any panic was thrown, calls the + provided callback. + + If action executes successfully, the result of `Panic.catch Any` is the + result of that action. Otherwise, it is the result of the provided + handler callback, executed with the caught panic as its first argument. + + Arguments: + - action: The code to execute that potentially panics. + - handler: The callback to handle any panics. + catch_primitive : Any -> (Caught_Panic -> Any) -> Any + catch_primitive ~action handler = @Builtin_Method "Panic.catch_primitive" + + ## PRIVATE + + Returns a raw representation of the stack trace attached to the provided + throwable. It can be a dataflow error, a panic or a native Java exception. + You probably want `Panic.get_attached_stack_trace` instead. + primitive_get_attached_stack_trace : Throwable -> Array + primitive_get_attached_stack_trace throwable = @Builtin_Method "Panic.primitive_get_attached_stack_trace" + + ## ADVANCED + UNSTABLE + + Returns the attached stack trace of the given throwable. Can be used to get + an Enso friendly stack trace from native Java exceptions. + + The ordering of the resulting vector is such that the top stack frame is the + first element. + get_attached_stack_trace : Caught_Panic | Throwable -> Vector.Vector Stack_Trace_Element + get_attached_stack_trace error = + throwable = case error of + Caught_Panic _ internal_original_exception -> internal_original_exception + throwable -> throwable + prim_stack = Panic.primitive_get_attached_stack_trace throwable + stack_with_prims = Vector.Vector prim_stack + stack_with_prims.map Runtime_Extensions.wrap_primitive_stack_trace_element + + ## Takes any value, and if it is a dataflow error, throws it as a Panic, + otherwise, returns the original value unchanged. + + Arguments: + - value: The value to rethrow any errors on as a panic. + + > Example + Rethrowing a dataflow error as a panic. + + import Standard.Examples + + example_rethrow = Panic.rethrow Examples.throw_error + rethrow : (Any ! Any) -> Any + rethrow value = value.catch Panic.throw + + ## Executes the provided action and if a panic matching the provided type was + thrown, calls the provided callback. + + If action executes successfully, the result of `Panic.catch` is the result of + that action. Otherwise, if a matching panic is thrown from within the action, + the result is obtained by calling the provided handler callback. Any + non-matching panics are forwarded without changes. + + Arguments: + - panic_type: The expected panic type. It can either be an Enso type or a + Java class. If the Java class is provided, `Polyglot_Error` containing a + Java exception of this class will be matched. + - action: The code to execute that potentially panics. + - handler: The callback to handle the panics. The callback will be provided + with a `Caught_Panic` instance encapsulating the `payload` of the caught + panic and its stacktrace. + + > Example + Handling a specific type of panic. + + Panic.catch Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "Oh no!" Nothing)) error-> + "Caught an `Illegal_Argument_Error`: "+error.payload.message + + > Example + Handling any panic. + + Panic.catch Any (Panic.throw (Illegal_Argument_Error "Oh no!" Nothing)) error-> + "Caught some panic!" + + > Example + Convert a string to an integer, catching the Java `NumberFormatException` + and converting it to a more Enso-friendly dataflow error. + + polyglot java import java.lang.Long + polyglot java import java.lang.NumberFormatException + parse str = + Panic.catch NumberFormatException (Long.parseLong str) caught_panic-> + Error.throw (Illegal_Argument_Error "The provided string is not a valid number: "+caught_panic.payload.cause.getMessage) + catch : Any -> Any -> (Caught_Panic -> Any) -> Any + catch panic_type ~action handler = + Panic.catch_primitive action caught_panic-> + case Meta.get_polyglot_language panic_type == "java" of + False -> case caught_panic.payload.is_a panic_type of + True -> handler caught_panic + False -> Panic.throw caught_panic + True -> case caught_panic.payload of + Polyglot_Error java_exception -> + case Java.is_instance java_exception panic_type of + True -> handler caught_panic + False -> Panic.throw caught_panic + _ -> Panic.throw caught_panic + + ## Executes the provided action and converts a possible panic matching any of + the provided types into a dataflow Error. + + If action executes successfully, the result of `Panic.recover` is the result + of that action. Otherwise, if it panicked with a type matching one of the + expected error types, that panic is returned as a dataflow error. Unexpected + panics are passed through as-is. it is the panic that was thrown after + conversion to a dataflow error. + + Arguments: + - expected_types: The types of expected panics which should be recovered. + This can either be a Vector of types or a single type. + - action: The code to execute that potentially panics. + + > Example + Converting an expected panic to a dataflow error. + + Panic.recover Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "Oh!" Nothing)) + + > Example + Converting one of many expected panic types to a dataflow error. + + Panic.recover [Illegal_Argument_Error, Illegal_State_Error] (Panic.throw (Illegal_Argument_Error "Oh!" Nothing)) + recover : (Vector.Vector Any | Any) -> Any -> Any + recover expected_types ~action = + types_to_check = case expected_types of + Vector.Vector _ -> expected_types + _ -> [expected_types] + Panic.catch Any action caught_panic-> + is_matched = types_to_check.exists typ-> + caught_panic.payload.is_a typ + case is_matched of + True -> caught_panic.convert_to_dataflow_error + False -> Panic.throw caught_panic + +## The runtime representation of a syntax error. + + Arguments: + - message: A description of the erroneous syntax. +@Builtin_Type +type Syntax_Error message + +## The runtime representation of a type error. + + Arguments: + - expected: The expected type at the error location. + - actual: The actual type at the error location. +@Builtin_Type +type Type_Error expected actual + +## The runtime representation of a compilation error. + + Arguments: + - message: A description of the erroneous state. +@Builtin_Type +type Compile_Error message + +## The error thrown when a there is no pattern to match on the scrutinee. + + Arguments: + - scrutinee: The scrutinee that failed to match. +@Builtin_Type +type Inexhaustive_Pattern_Match_Error scrutinee + +## The error thrown when the number of arguments provided to an operation + does not match the expected number of arguments. + + Arguments: + - expected: the expected number of arguments. + - actual: the actual number of arguments passed. +@Builtin_Type +type Arity_Error expected actual + +## The error thrown when the program attempts to read from a state slot that has + not yet been initialized. + + Arguments: + - key: The key for the state slot that was not initialized. +@Builtin_Type +type Uninitialized_State key + +## The error thrown when the specified symbol does not exist as a method on + the target. + + Arguments: + - target: The target on which the attempted method call was performed. + - symbol: The symbol that was attempted to be called on target. +@Builtin_Type +type No_Such_Method_Error target symbol + +## ADVANCED + UNSTABLE + + Returns the method name of the method that could not be found. + + > Example + Getting the method name from a no such method error. + + import Standard.Examples + + example_method_name = + error = Examples.no_such_method + error.method_name +No_Such_Method_Error.method_name : Text +No_Such_Method_Error.method_name = + Meta.meta this.symbol . name + + +## An error that occurred across a polyglot boundary. + + Arguments: + - cause: A polyglot object corresponding to the original error. +@Builtin_Type +type Polyglot_Error cause + +## An error that occurs when the enso_project function is called in a file + that is not part of a project. +@Builtin_Type +type Module_Not_In_Package_Error + +## An error for when an erroneous arithmetic computation takes place. + + Arguments: + - message: A description of the error condition. +@Builtin_Type +type Arithmetic_Error message + +## An error that occurs when a program requests a read from an array index + that is out of bounds in the array. + + Arguments: + - array: The array in which the index was requested. + - index: The index that was out of bounds. +@Builtin_Type +type Invalid_Array_Index_Error array index + +## An error that occurs when an object is used as a function in a function + call, but it cannot be called. + + Arguments: + - target: The called object. +@Builtin_Type +type Not_Invokable_Error target + +## An error that occurs when arguments used in a function call are invalid + types for the function. + + Arguments: + - arguments: The passed arguments. +@Builtin_Type +type Unsupported_Argument_Types arguments + +## An error that occurs when the specified module cannot be found. + + Arguments: + - name: The module searched for. +@Builtin_Type +type Module_Does_Not_Exist name + +## An error that occurs when the specified value cannot be converted to a given type +## FIXME: please check + + Arguments: + - target: ... +@Builtin_Type +type Invalid_Conversion_Target_Error target + +## An error that occurs when the conversion from one type to another does not exist +## FIXME: please check + + Arguments: + - target: ... + - that: ... + - conversion: ... +@Builtin_Type +type No_Such_Conversion_Error + +## UNSTABLE + + A type used to represent that something has not yet been implemented. + + Arguments: + - message: The message describing what implementation is missing. +type Unimplemented_Error message + +## UNSTABLE + + Converts the unimplemented error to a human-readable error message. +Unimplemented_Error.to_display_text : Text +Unimplemented_Error.to_display_text = "An implementation is missing: " + this.message + +## ADVANCED + + A function that can be used to indicate that something hasn't been + implemented yet. + + Arguments: + - message: A description of what implementation is missing. + + > Example + Throwing an error to show that something is unimplemented. + + import Standard.Base.Error.Extensions + + example_unimplemented = Extensions.unimplemented +unimplemented : Text -> Void +unimplemented message="" = Panic.throw (Unimplemented_Error message) \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso index 93a681c70645..cd4367e8d975 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso @@ -1,176 +1,6 @@ from Standard.Base import all import Standard.Builtins -from Standard.Base.Runtime.Extensions as Runtime_Extensions import Stack_Trace_Element -## ADVANCED - UNSTABLE - Returns the method name of the method that could not be found. - > Example - Getting the method name from a no such method error. - - import Standard.Examples - - example_method_name = - error = Examples.no_such_method - error.method_name -No_Such_Method_Error.method_name : Text -No_Such_Method_Error.method_name = - Meta.meta this.symbol . name - -## UNSTABLE - - A type used to represent that something has not yet been implemented. - - Arguments: - - message: The message describing what implementation is missing. -type Unimplemented_Error message - -## UNSTABLE - - Converts the unimplemented error to a human-readable error message. -Unimplemented_Error.to_display_text : Text -Unimplemented_Error.to_display_text = "An implementation is missing: " + this.message - -## ADVANCED - - A function that can be used to indicate that something hasn't been - implemented yet. - - Arguments: - - message: A description of what implementation is missing. - - > Example - Throwing an error to show that something is unimplemented. - - import Standard.Base.Error.Extensions - - example_unimplemented = Extensions.unimplemented -unimplemented : Text -> Void -unimplemented message="" = Panic.throw (Unimplemented_Error message) - -## ADVANCED - UNSTABLE - - Returns the attached stack trace of the given throwable. Can be used to get - an Enso friendly stack trace from native Java exceptions. - - The ordering of the resulting vector is such that the top stack frame is the - first element. -Panic.get_attached_stack_trace : Caught_Panic | Throwable -> Vector.Vector Stack_Trace_Element -Panic.get_attached_stack_trace error = - throwable = case error of - Caught_Panic _ internal_original_exception -> internal_original_exception - throwable -> throwable - prim_stack = Panic.primitive_get_attached_stack_trace throwable - stack_with_prims = Vector.Vector prim_stack - stack_with_prims.map Runtime_Extensions.wrap_primitive_stack_trace_element - -## Takes any value, and if it is a dataflow error, throws it as a Panic, - otherwise, returns the original value unchanged. - - Arguments: - - value: The value to rethrow any errors on as a panic. - - > Example - Rethrowing a dataflow error as a panic. - - import Standard.Examples - - example_rethrow = Panic.rethrow Examples.throw_error -Panic.rethrow : (Any ! Any) -> Any -Panic.rethrow value = value.catch Panic.throw - -## Returns the stack trace of the caught panic. -Caught_Panic.stack_trace : Vector.Vector Stack_Trace_Element -Caught_Panic.stack_trace = - Panic.get_attached_stack_trace this - -## Executes the provided action and if a panic matching the provided type was - thrown, calls the provided callback. - - If action executes successfully, the result of `Panic.catch` is the result of - that action. Otherwise, if a matching panic is thrown from within the action, - the result is obtained by calling the provided handler callback. Any - non-matching panics are forwarded without changes. - - Arguments: - - panic_type: The expected panic type. It can either be an Enso type or a - Java class. If the Java class is provided, `Polyglot_Error` containing a - Java exception of this class will be matched. - - action: The code to execute that potentially panics. - - handler: The callback to handle the panics. The callback will be provided - with a `Caught_Panic` instance encapsulating the `payload` of the caught - panic and its stacktrace. - - > Example - Handling a specific type of panic. - - Panic.catch Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "Oh no!" Nothing)) error-> - "Caught an `Illegal_Argument_Error`: "+error.payload.message - - > Example - Handling any panic. - - Panic.catch Any (Panic.throw (Illegal_Argument_Error "Oh no!" Nothing)) error-> - "Caught some panic!" - - > Example - Convert a string to an integer, catching the Java `NumberFormatException` - and converting it to a more Enso-friendly dataflow error. - - polyglot java import java.lang.Long - polyglot java import java.lang.NumberFormatException - parse str = - Panic.catch NumberFormatException (Long.parseLong str) caught_panic-> - Error.throw (Illegal_Argument_Error "The provided string is not a valid number: "+caught_panic.payload.cause.getMessage) -Panic.catch : Any -> Any -> (Caught_Panic -> Any) -> Any -Panic.catch panic_type ~action handler = - Panic.catch_primitive action caught_panic-> - case Meta.get_polyglot_language panic_type == "java" of - False -> case caught_panic.payload.is_a panic_type of - True -> handler caught_panic - False -> Panic.throw caught_panic - True -> case caught_panic.payload of - Polyglot_Error java_exception -> - case Java.is_instance java_exception panic_type of - True -> handler caught_panic - False -> Panic.throw caught_panic - _ -> Panic.throw caught_panic - -## Executes the provided action and converts a possible panic matching any of - the provided types into a dataflow Error. - - If action executes successfully, the result of `Panic.recover` is the result - of that action. Otherwise, if it panicked with a type matching one of the - expected error types, that panic is returned as a dataflow error. Unexpected - panics are passed through as-is. it is the panic that was thrown after - conversion to a dataflow error. - - Arguments: - - expected_types: The types of expected panics which should be recovered. - This can either be a Vector of types or a single type. - - action: The code to execute that potentially panics. - - > Example - Converting an expected panic to a dataflow error. - - Panic.recover Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "Oh!" Nothing)) - - > Example - Converting one of many expected panic types to a dataflow error. - - Panic.recover [Illegal_Argument_Error, Illegal_State_Error] (Panic.throw (Illegal_Argument_Error "Oh!" Nothing)) -Panic.recover : (Vector.Vector Any | Any) -> Any -> Any -Panic.recover expected_types ~action = - types_to_check = case expected_types of - Vector.Vector _ -> expected_types - _ -> [expected_types] - Panic.catch Any action caught_panic-> - is_matched = types_to_check.exists typ-> - caught_panic.payload.is_a typ - case is_matched of - True -> caught_panic.convert_to_dataflow_error - False -> Panic.throw caught_panic diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 8074408be1b7..79554a062182 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -14,6 +14,7 @@ import project.Data.Ordering.Sort_Order import project.Data.Pair import project.Data.Range import project.Data.Ref +import project.Data.Text.Text import project.Data.Text.Extensions import project.Data.Text.Matching import project.Data.Vector @@ -30,7 +31,7 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Arithmetic_Error +from Standard.Builtins import Nothing, Number, Integer export project.Data.Interval export project.Data.Json @@ -66,6 +67,7 @@ from project.Data.Range export Range https://www.pivotaltracker.com/story/show/181309938 from project.Data.Text.Extensions export Text, Split_Kind, Line_Ending_Style, Case, Location from project.Data.Text.Matching export Case_Insensitive, Text_Matcher, Regex_Matcher +from project.Data.Text.Text export all from project.Error.Common export all from project.Error.Extensions export all from project.Meta.Enso_Project export all diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java new file mode 100644 index 000000000000..3b7bcb4ef121 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "message") +public class ArithmeticError extends AtomConstructor { + public ArithmeticError(ModuleScope definitionScope) { + super("Arithmetic_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java new file mode 100644 index 000000000000..a1b4d3ca9108 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "expected_min,expected_max,actual") +public class ArityError extends AtomConstructor { + public ArityError(ModuleScope definitionScope) { + super("Arity_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java new file mode 100644 index 000000000000..9251c25cf2f9 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params="payload,internal_original_exception") +public class CaughtPanic extends AtomConstructor { + public CaughtPanic(ModuleScope definitionScope) { + super("Caught_Panic", definitionScope, true); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java new file mode 100644 index 000000000000..3bae6f4f1c24 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "message") +public class CompileError extends AtomConstructor { + public CompileError(ModuleScope definitionScope) { + super("Compile_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java new file mode 100644 index 000000000000..caea977c7ade --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "scrutinee") +public class InexhaustivePatternMatchError extends AtomConstructor { + public InexhaustivePatternMatchError(ModuleScope definitionScope) { + super("Inexhaustive_Pattern_Match_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java new file mode 100644 index 000000000000..f6092cc5191a --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "array,index") +public class InvalidArrayIndexError extends AtomConstructor { + public InvalidArrayIndexError(ModuleScope definitionScope) { + super("Invalid_Array_Index_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java new file mode 100644 index 000000000000..11551ef29aa0 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "target") +public class InvalidConversionTargetError extends AtomConstructor { + public InvalidConversionTargetError(ModuleScope definitionScope) { + super("Invalid_Conversion_Target_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java new file mode 100644 index 000000000000..208b3d52374d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "name") +public class ModuleDoesNotExist extends AtomConstructor { + public ModuleDoesNotExist(ModuleScope definitionScope) { + super("Module_Does_Not_Exist", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java new file mode 100644 index 000000000000..b24f5b6a15f5 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class ModuleNotInPackageError extends AtomConstructor { + public ModuleNotInPackageError(ModuleScope definitionScope) { + super("Module_Not_In_Package_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java new file mode 100644 index 000000000000..4d88a4d90928 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "target,that,conversion") +public class NoSuchConversionError extends AtomConstructor { + public NoSuchConversionError(ModuleScope definitionScope) { + super("No_Such_Conversion_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java new file mode 100644 index 000000000000..49139ddf6902 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "target,symbol") +public class NoSuchMethodError extends AtomConstructor { + public NoSuchMethodError(ModuleScope definitionScope) { + super("No_Such_Method_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java new file mode 100644 index 000000000000..a0ea05797287 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "target") +public class NotInvokableError extends AtomConstructor { + public NotInvokableError(ModuleScope definitionScope) { + super("Not_Invokable_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java new file mode 100644 index 000000000000..4bf6c82bc621 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Panic extends AtomConstructor { + public Panic(ModuleScope definitionScope) { + super("Panic", definitionScope, true); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java new file mode 100644 index 000000000000..ebd16615df44 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "cause") +public class PolyglotError extends AtomConstructor { + public PolyglotError(ModuleScope definitionScope) { + super("Polyglot_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java new file mode 100644 index 000000000000..0dea752ace3f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "message") +public class SyntaxError extends AtomConstructor { + public SyntaxError(ModuleScope definitionScope) { + super("Syntax_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java new file mode 100644 index 000000000000..91d7dcbc8080 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "expected,actual,name") +public class TypeError extends AtomConstructor { + public TypeError(ModuleScope definitionScope) { + super("Type_Error", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java new file mode 100644 index 000000000000..4d6a4863340c --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "key") +public class UninitializedState extends AtomConstructor { + public UninitializedState(ModuleScope definitionScope) { + super("Uninitialized_State", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java new file mode 100644 index 000000000000..724bd11b8c06 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java @@ -0,0 +1,13 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType(params = "arguments") +public class UnsupportedArgumentTypes extends AtomConstructor { + public UnsupportedArgumentTypes(ModuleScope definitionScope) { + super("Unsupported_Argument_Types", definitionScope, true); + } +} + diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/NoSuchConversionErrorToDisplayTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/NoSuchConversionErrorToDisplayTextNode.java index e5627c3175d0..a939237850da 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/NoSuchConversionErrorToDisplayTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/NoSuchConversionErrorToDisplayTextNode.java @@ -11,7 +11,7 @@ import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.type.TypesGen; -@BuiltinMethod(type = "No_Such_Method_Error", name = "to_display_text") +@BuiltinMethod(type = "No_Such_Conversion_Error", name = "to_display_text") public abstract class NoSuchConversionErrorToDisplayTextNode extends Node { static NoSuchConversionErrorToDisplayTextNode build() { return NoSuchConversionErrorToDisplayTextNodeGen.create(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java new file mode 100644 index 000000000000..6343eb3232ce --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin.text; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class PrimTextHelper extends AtomConstructor { + public PrimTextHelper(ModuleScope definitionScope) { + super("Prim_Text_Helper", definitionScope, true); + } +} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java new file mode 100644 index 000000000000..4519286370de --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin.text; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.scope.ModuleScope; + +@BuiltinType +public class Text extends AtomConstructor { + public Text(ModuleScope definitionScope) { + super("Text", definitionScope, true); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectStringNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectStringNode.java index 6db1341fef16..d4de28bbad85 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectStringNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectStringNode.java @@ -37,7 +37,7 @@ String doFallback(Object str) { return library.asString(str); } catch (UnsupportedMessageException e) { Builtins builtins = Context.get(this).getBuiltins(); - Atom err = builtins.error().makeTypeError(builtins.text().getText(), str, "str"); + Atom err = builtins.error().makeTypeError(builtins.text(), str, "str"); throw new PanicException(err, this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectTextNode.java index 2a4c0d432da5..2613ff7abd2a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/ExpectTextNode.java @@ -38,7 +38,7 @@ Text doFallback(Object str) { return Text.create(library.asString(str)); } catch (UnsupportedMessageException e) { Builtins builtins = Context.get(this).getBuiltins(); - Atom err = builtins.error().makeTypeError(builtins.text().getText(), str, "str"); + Atom err = builtins.error().makeTypeError(builtins.text(), str, "str"); throw new PanicException(err, this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index ae933245f2e3..671e11aa1e42 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -39,6 +39,7 @@ import org.enso.interpreter.node.expression.builtin.state.GetStateMethodGen; import org.enso.interpreter.node.expression.builtin.state.PutStateMethodGen; import org.enso.interpreter.node.expression.builtin.state.RunStateMethodGen; +import org.enso.interpreter.node.expression.builtin.text.Text; import org.enso.interpreter.node.expression.builtin.thread.WithInterruptHandlerMethodGen; import org.enso.interpreter.node.expression.builtin.unsafe.SetAtomFieldMethodGen; import org.enso.interpreter.runtime.Context; @@ -74,8 +75,6 @@ public static class Debug { private final AtomConstructor projectDescription; private final AtomConstructor function; private final AtomConstructor nothing; - private final AtomConstructor panic; - private final AtomConstructor caughtPanic; private final Error error; private final Module module; @@ -84,7 +83,6 @@ public static class Debug { private final Ordering ordering; private final Resource resource; private final System system; - private final Text text; private final Special special; /** @@ -107,21 +105,13 @@ public Builtins(Context context) { new ArgumentDefinition( 0, "prim_root_file", ArgumentDefinition.ExecutionMode.EXECUTE), new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); - error = new Error(language, scope); + error = new Error(this); function = new AtomConstructor("Function", scope).initializeFields(); nothing = new AtomConstructor("Nothing", scope).initializeFields(); number = new Number(language, scope); ordering = new Ordering(language, scope); - panic = new AtomConstructor("Panic", scope).initializeFields(); - caughtPanic = - new AtomConstructor("Caught_Panic", scope) - .initializeFields( - new ArgumentDefinition(0, "payload", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition( - 1, "internal_original_exception", ArgumentDefinition.ExecutionMode.EXECUTE)); resource = new Resource(language, scope); system = new System(language, scope); - text = new Text(language, scope); special = new Special(language); AtomConstructor io = new AtomConstructor("IO", scope).initializeFields(); @@ -137,8 +127,6 @@ public Builtins(Context context) { scope.registerConstructor(io); scope.registerConstructor(primIo); - scope.registerConstructor(panic); - scope.registerConstructor(caughtPanic); scope.registerConstructor(state); scope.registerConstructor(debug); scope.registerConstructor(projectDescription); @@ -161,13 +149,6 @@ public Builtins(Context context) { scope.registerMethod( runtime, "primitive_get_stack_trace", GetStackTraceMethodGen.makeFunction(language)); - scope.registerMethod(panic, "throw", ThrowPanicMethodGen.makeFunction(language)); - scope.registerMethod(panic, "catch_primitive", CatchPanicMethodGen.makeFunction(language)); - scope.registerMethod( - panic, - "primitive_get_attached_stack_trace", - GetAttachedStackTraceMethodGen.makeFunction(language)); - scope.registerMethod(caughtPanic, "convert_to_dataflow_error", CaughtPanicConvertToDataflowErrorMethodGen.makeFunction(language)); scope.registerMethod(state, "get", GetStateMethodGen.makeFunction(language)); scope.registerMethod(state, "put", PutStateMethodGen.makeFunction(language)); scope.registerMethod(state, "run", RunStateMethodGen.makeFunction(language)); @@ -345,6 +326,11 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } + public AtomConstructor getBuiltinType(Class clazz) { + String snakeCaseName = clazz.getSimpleName().replaceAll("([^_A-Z])([A-Z])", "$1_$2"); + return getBuiltinType(snakeCaseName); + } + public AtomConstructor getBuiltinType(String name) { return builtinTypes.get(name); } @@ -363,8 +349,8 @@ public AtomConstructor nothing() { * * @return the {@code Text} part of builtins. */ - public Text text() { - return text; + public AtomConstructor text() { + return getBuiltinType(Text.class); } /** @@ -451,7 +437,12 @@ public AtomConstructor polyglot() { /** @return the {@code Caught_Panic} atom constructor */ public AtomConstructor caughtPanic() { - return caughtPanic; + return builtinTypes.get("Caught_Panic"); + } + + /** @return the {@code Panic} atom constructor */ + public AtomConstructor panic() { + return builtinTypes.get("Panic"); } /** @return the container for ordering-related builtins */ @@ -511,11 +502,11 @@ public Atom fromTypeSystem(String typeName) { case Constants.NUMBER: return number.getNumber().newInstance(); case Constants.PANIC: - return panic.newInstance(); + return panic().newInstance(); case Constants.REF: return ref().newInstance(); case Constants.TEXT: - return text.getText().newInstance(); + return getBuiltinType(Text.class).newInstance(); default: return null; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index b72fc979801e..5b3900851095 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java @@ -1,37 +1,21 @@ package org.enso.interpreter.runtime.builtin; -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.error.displaytext.*; +import org.enso.interpreter.node.expression.builtin.error.*; +import org.enso.interpreter.node.expression.builtin.error.NoSuchMethodError; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.scope.ModuleScope; /** Container for builtin Error types */ public class Error { - private final AtomConstructor syntaxError; - private final AtomConstructor typeError; - private final AtomConstructor compileError; - private final AtomConstructor inexhaustivePatternMatchError; - private final AtomConstructor uninitializedState; - private final AtomConstructor noSuchMethodError; - private final AtomConstructor noSuchConversionError; - private final AtomConstructor polyglotError; - private final AtomConstructor moduleNotInPackageError; - private final AtomConstructor arithmeticError; - private final AtomConstructor invalidArrayIndexError; - private final AtomConstructor arityError; - private final AtomConstructor unsupportedArgumentsError; - private final AtomConstructor moduleDoesNotExistError; - private final AtomConstructor notInvokableError; - private final AtomConstructor invalidConversionTargetError; - private final Atom arithmeticErrorShiftTooBig; - private final Atom arithmeticErrorDivideByZero; + private Builtins builtins; + // FXIME: compilation final + private Atom arithmeticErrorShiftTooBig; + private Atom arithmeticErrorDivideByZero; private static final Text shiftTooBigMessage = Text.create("Shift amount too large."); private static final Text divideByZeroMessage = Text.create("Cannot divide by zero."); @@ -42,184 +26,40 @@ public class Error { * @param language the current language instance. * @param scope the scope to register constructors in. */ - public Error(Language language, ModuleScope scope) { - syntaxError = - new AtomConstructor("Syntax_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "message", ArgumentDefinition.ExecutionMode.EXECUTE)); - typeError = - new AtomConstructor("Type_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "expected", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "actual", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(2, "name", ArgumentDefinition.ExecutionMode.EXECUTE)); - compileError = - new AtomConstructor("Compile_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "message", ArgumentDefinition.ExecutionMode.EXECUTE)); - inexhaustivePatternMatchError = - new AtomConstructor("Inexhaustive_Pattern_Match_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "scrutinee", ArgumentDefinition.ExecutionMode.EXECUTE)); - uninitializedState = - new AtomConstructor("Uninitialized_State", scope) - .initializeFields( - new ArgumentDefinition(0, "key", ArgumentDefinition.ExecutionMode.EXECUTE)); - noSuchMethodError = - new AtomConstructor("No_Such_Method_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "target", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "symbol", ArgumentDefinition.ExecutionMode.EXECUTE)); - - noSuchConversionError = - new AtomConstructor("No_Such_Conversion_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "target", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "that", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(2, "conversion", ArgumentDefinition.ExecutionMode.EXECUTE)); - - invalidConversionTargetError = - new AtomConstructor("Invalid_Conversion_Target_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "target", ArgumentDefinition.ExecutionMode.EXECUTE)); - - polyglotError = - new AtomConstructor("Polyglot_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "cause", ArgumentDefinition.ExecutionMode.EXECUTE)); - moduleNotInPackageError = - new AtomConstructor("Module_Not_In_Package_Error", scope).initializeFields(); - arithmeticError = - new AtomConstructor("Arithmetic_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "message", ArgumentDefinition.ExecutionMode.EXECUTE)); - arithmeticErrorShiftTooBig = arithmeticError.newInstance(shiftTooBigMessage); - arithmeticErrorDivideByZero = arithmeticError.newInstance(divideByZeroMessage); - invalidArrayIndexError = - new AtomConstructor("Invalid_Array_Index_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "array", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "index", ArgumentDefinition.ExecutionMode.EXECUTE)); - arityError = - new AtomConstructor("Arity_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "expected_min", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "expected_max", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(2, "actual", ArgumentDefinition.ExecutionMode.EXECUTE)); - - unsupportedArgumentsError = - new AtomConstructor("Unsupported_Argument_Types", scope) - .initializeFields( - new ArgumentDefinition(0, "arguments", ArgumentDefinition.ExecutionMode.EXECUTE)); - moduleDoesNotExistError = - new AtomConstructor("Module_Does_Not_Exist", scope) - .initializeFields( - new ArgumentDefinition(0, "name", ArgumentDefinition.ExecutionMode.EXECUTE)); - notInvokableError = - new AtomConstructor("Not_Invokable_Error", scope) - .initializeFields( - new ArgumentDefinition(0, "target", ArgumentDefinition.ExecutionMode.EXECUTE)); - - scope.registerConstructor(arityError); - scope.registerMethod( - arityError, "to_display_text", ArityErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(syntaxError); - scope.registerMethod( - syntaxError, "to_display_text", SyntaxErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(typeError); - scope.registerMethod( - typeError, "to_display_text", TypeErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(compileError); - scope.registerMethod( - compileError, "to_display_text", CompileErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(inexhaustivePatternMatchError); - scope.registerMethod( - inexhaustivePatternMatchError, - "to_display_text", - InexhaustivePatternMatchErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(uninitializedState); - scope.registerMethod( - uninitializedState, - "to_display_text", - UninitializedStateErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(noSuchMethodError); - scope.registerMethod( - noSuchMethodError, - "to_display_text", - NoSuchMethodErrorToDisplayTextMethodGen.makeFunction(language)); - - scope.registerConstructor(noSuchConversionError); - scope.registerMethod( - noSuchConversionError, - "to_display_text", - NoSuchConversionErrorToDisplayTextMethodGen.makeFunction(language)); - - scope.registerConstructor(invalidConversionTargetError); - scope.registerMethod( - invalidConversionTargetError, - "to_display_text", - InvalidConversionTargetErrorToDisplayTextMethodGen.makeFunction(language)); - - scope.registerConstructor(polyglotError); - scope.registerMethod( - polyglotError, - "to_display_text", - PolyglotErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(moduleNotInPackageError); - scope.registerMethod( - moduleNotInPackageError, - "to_display_text", - ModuleNotInPackageErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(arithmeticError); - scope.registerMethod( - arithmeticError, - "to_display_text", - ArithmeticErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(invalidArrayIndexError); - scope.registerMethod( - invalidArrayIndexError, - "to_display_text", - InvalidArrayIndexErrorToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(unsupportedArgumentsError); - scope.registerMethod( - unsupportedArgumentsError, - "to_display_text", - UnsupportedArgumentTypesToDisplayTextMethodGen.makeFunction(language)); - scope.registerConstructor(notInvokableError); - scope.registerMethod( - notInvokableError, - "to_display_text", - NotInvokableErrorToDisplayTextMethodGen.makeFunction(language)); + public Error(Builtins builtins) { + this.builtins = builtins; + arithmeticErrorShiftTooBig = null; + arithmeticErrorDivideByZero = null; } /** @return the builtin {@code Syntax_Error} atom constructor. */ public AtomConstructor syntaxError() { - return syntaxError; + return builtins.getBuiltinType(SyntaxError.class); } /** @return the builtin {@code Type_Error} atom constructor. */ public AtomConstructor typeError() { - return typeError; + return builtins.getBuiltinType(TypeError.class); } /** @return the builtin {@code Compile_Error} atom constructor. */ public AtomConstructor compileError() { - return compileError; + return builtins.getBuiltinType(CompileError.class); } /** @return the builtin {@code Inexhaustive_Pattern_Match_Error} atom constructor. */ public AtomConstructor inexhaustivePatternMatchError() { - return inexhaustivePatternMatchError; + return builtins.getBuiltinType(InexhaustivePatternMatchError.class); } /** @return the builtin {@code Uninitialized_State} atom constructor. */ public AtomConstructor uninitializedState() { - return uninitializedState; + return builtins.getBuiltinType(UninitializedState.class); } /** @return the builtin {@code Module_Not_In_Package_Error} atom constructor. */ public AtomConstructor moduleNotInPackageError() { - return moduleNotInPackageError; + return builtins.getBuiltinType(ModuleNotInPackageError.class); } /** @@ -230,16 +70,16 @@ public AtomConstructor moduleNotInPackageError() { * @return a runtime representation of the error */ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { - return noSuchMethodError.newInstance(target, symbol); + return builtins.getBuiltinType(NoSuchMethodError.class).newInstance(target, symbol); } public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { - return noSuchConversionError.newInstance(target, that, conversion); + return builtins.getBuiltinType(NoSuchConversionError.class).newInstance(target, that, conversion); } public Atom makeInvalidConversionTargetError(Object target) { - return invalidConversionTargetError.newInstance(target); + return builtins.getBuiltinType(InvalidConversionTargetError.class).newInstance(target); } /** @@ -251,7 +91,7 @@ public Atom makeInvalidConversionTargetError(Object target) { * @return a runtime representation of the error. */ public Atom makeTypeError(Object expected, Object actual, String name) { - return typeError.newInstance(expected, actual, Text.create(name)); + return builtins.getBuiltinType(TypeError.class).newInstance(expected, actual, Text.create(name)); } /** @@ -261,7 +101,7 @@ public Atom makeTypeError(Object expected, Object actual, String name) { * @return a runtime representation of the polyglot error. */ public Atom makePolyglotError(Object cause) { - return polyglotError.newInstance(cause); + return builtins.getBuiltinType(PolyglotError.class).newInstance(cause); } /** @@ -271,16 +111,22 @@ public Atom makePolyglotError(Object cause) { * @return a runtime representation of the arithmetic error */ public Atom makeArithmeticError(Text reason) { - return arithmeticError.newInstance(reason); + return builtins.getBuiltinType(ArithmeticError.class).newInstance(reason); } /** @return An arithmetic error representing a too-large shift for the bit shift. */ public Atom getShiftAmountTooLargeError() { + if (arithmeticErrorShiftTooBig == null) { + arithmeticErrorShiftTooBig = makeArithmeticError(shiftTooBigMessage); + } return arithmeticErrorShiftTooBig; } /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { + if (arithmeticErrorDivideByZero == null) { + arithmeticErrorDivideByZero = makeArithmeticError(divideByZeroMessage); + } return arithmeticErrorDivideByZero; } @@ -290,7 +136,7 @@ public Atom getDivideByZeroError() { * @return An error representing that the {@code index} is not valid in {@code array} */ public Atom makeInvalidArrayIndexError(Object array, Object index) { - return invalidArrayIndexError.newInstance(array, index); + return builtins.getBuiltinType(InvalidArrayIndexError.class).newInstance(array, index); } /** @@ -300,7 +146,7 @@ public Atom makeInvalidArrayIndexError(Object array, Object index) { * @return an error informing about the arity being mismatched */ public Atom makeArityError(long expected_min, long expected_max, long actual) { - return arityError.newInstance(expected_min, expected_max, actual); + return builtins.getBuiltinType(ArityError.class).newInstance(expected_min, expected_max, actual); } /** @@ -309,7 +155,7 @@ public Atom makeArityError(long expected_min, long expected_max, long actual) { * given method callp */ public Atom makeUnsupportedArgumentsError(Object[] args) { - return unsupportedArgumentsError.newInstance(new Array(args)); + return builtins.getBuiltinType(UnsupportedArgumentTypes.class).newInstance(new Array(args)); } /** @@ -317,7 +163,7 @@ public Atom makeUnsupportedArgumentsError(Object[] args) { * @return a module does not exist error */ public Atom makeModuleDoesNotExistError(String name) { - return moduleDoesNotExistError.newInstance(Text.create(name)); + return builtins.getBuiltinType(ModuleDoesNotExist.class).newInstance(Text.create(name)); } /** @@ -325,6 +171,6 @@ public Atom makeModuleDoesNotExistError(String name) { * @return a not invokable error */ public Atom makeNotInvokableError(Object target) { - return notInvokableError.newInstance(target); + return builtins.getBuiltinType(NotInvokableError.class).newInstance(target); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Text.java deleted file mode 100644 index f9b993655468..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Text.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.text.ConcatMethodGen; -import org.enso.interpreter.node.expression.builtin.text.OptimizeMethodGen; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** A container class for all Text-related stdlib builtins. */ -public class Text { - private final AtomConstructor text; - - /** - * Creates and registers all the text constructors and methods. - * - * @param language the current language instance. - * @param scope the scope to register constructors and methods in. - */ - public Text(Language language, ModuleScope scope) { - text = new AtomConstructor("Text", scope).initializeFields(); - scope.registerConstructor(text); - AtomConstructor primTextHelpers = - new AtomConstructor("Prim_Text_Helper", scope).initializeFields(); - scope.registerConstructor(primTextHelpers); - - scope.registerMethod(text, "+", ConcatMethodGen.makeFunction(language)); - scope.registerMethod(primTextHelpers, "optimize", OptimizeMethodGen.makeFunction(language)); - } - - /** @return the Text atom constructor. */ - public AtomConstructor getText() { - return text; - } -} 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 f2104108d3d4..2b9d054159df 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 @@ -190,7 +190,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().text().getText(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().text(), context.getBuiltins().any()); } static Context getContext() { @@ -243,7 +243,7 @@ static class GetConversionFunction { static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { Context context = getContext(); return conversion.resolveFor( - target, context.getBuiltins().text().getText(), context.getBuiltins().any()); + target, context.getBuiltins().text(), context.getBuiltins().any()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index e49bc859fad4..47176e0d2501 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -14,9 +14,9 @@ public class Constants { public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; public static final String NOTHING = "Standard.Builtins.Main.Nothing"; public static final String NUMBER = "Standard.Builtins.Main.Number"; - public static final String PANIC = "Standard.Builtins.Main.Panic"; + public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; - public static final String TEXT = "Standard.Builtins.Main.Text"; + public static final String TEXT = "Standard.Base.Data.Text.Text"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; } diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 13d82a8bcc97..b8453dc9857d 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -75,189 +75,6 @@ type Prim_Warning get_reassignments : Prim_Warning -> Any get_reassignments warn = @Builtin_Method "Prim_Warning.get_reassignments" -## The runtime representation of a syntax error. - - Arguments: - - message: A description of the erroneous syntax. -@Builtin_Type -type Syntax_Error message - -## The runtime representation of a type error. - - Arguments: - - expected: The expected type at the error location. - - actual: The actual type at the error location. -@Builtin_Type -type Type_Error expected actual - -## The runtime representation of a compilation error. - - Arguments: - - message: A description of the erroneous state. -@Builtin_Type -type Compile_Error message - -## The error thrown when a there is no pattern to match on the scrutinee. - - Arguments: - - scrutinee: The scrutinee that failed to match. -@Builtin_Type -type Inexhaustive_Pattern_Match_Error scrutinee - -## The error thrown when the number of arguments provided to an operation - does not match the expected number of arguments. - - Arguments: - - expected: the expected number of arguments. - - actual: the actual number of arguments passed. -@Builtin_Type -type Arity_Error expected actual - -## The error thrown when the program attempts to read from a state slot that has - not yet been initialized. - - Arguments: - - key: The key for the state slot that was not initialized. -@Builtin_Type -type Uninitialized_State key - -## The error thrown when the specified symbol does not exist as a method on - the target. - - Arguments: - - target: The target on which the attempted method call was performed. - - symbol: The symbol that was attempted to be called on target. -@Builtin_Type -type No_Such_Method_Error target symbol - -## An error that occurred across a polyglot boundary. - - Arguments: - - cause: A polyglot object corresponding to the original error. -@Builtin_Type -type Polyglot_Error cause - -## An error that occurs when the enso_project function is called in a file - that is not part of a project. -@Builtin_Type -type Module_Not_In_Package_Error - -## An error for when an erroneous arithmetic computation takes place. - - Arguments: - - message: A description of the error condition. -@Builtin_Type -type Arithmetic_Error message - -## An error that occurs when a program requests a read from an array index - that is out of bounds in the array. - - Arguments: - - array: The array in which the index was requested. - - index: The index that was out of bounds. -@Builtin_Type -type Invalid_Array_Index_Error array index - -## An error that occurs when an object is used as a function in a function - call, but it cannot be called. - - Arguments: - - target: The called object. -@Builtin_Type -type Not_Invokable_Error target - -## An error that occurs when arguments used in a function call are invalid - types for the function. - - Arguments: - - arguments: The passed arguments. -@Builtin_Type -type Unsupported_Argument_Types arguments - -## An error that occurs when the specified module cannot be found. - - Arguments: - - name: The module searched for. -@Builtin_Type -type Module_Does_Not_Exist name - -## Panics. -type Panic - - ## A panic is an error condition that is based _outside_ of the normal - program control flow. - - Panics "bubble up" through the program until they reach either an - invocation of Panic.recover Any or the program's main method. An unhandled - panic in main will terminate the program. - - ? Dataflow Errors or Panics - Panics are designed to be used for unrecoverable situations that need - to be handled through non-linear control flow mechanisms. - @Builtin_Type - type Panic - - ## Throws a new panic with the provided payload. - - Arguments: - - payload: The contents of the panic to be thrown. If the payload is a - `Caught_Panic` or a raw Java exception, instead of throwing a new panic - with it as a payload, the original exception is rethrown, preserving - its stacktrace. - - > Example - Throwing a panic containing the text "Oh no!". - - Panic.throw "Oh no!" - - > Example - Use together with `Panic.catch` to catch only specific types of errors - and rethrow any others, without affecting their stacktraces. - - Panic.catch Any (Panic.throw "foo") caught_panic-> case caught_panic.payload of - Illegal_Argument_Error message _ -> "Illegal arguments were provided: "+message - other_panic -> Panic.throw other_panic - throw : Any -> Panic - throw payload = @Builtin_Method "Panic.throw" - - ## PRIVATE - Executes the provided action and if any panic was thrown, calls the - provided callback. - - If action executes successfully, the result of `Panic.catch Any` is the - result of that action. Otherwise, it is the result of the provided - handler callback, executed with the caught panic as its first argument. - - Arguments: - - action: The code to execute that potentially panics. - - handler: The callback to handle any panics. - catch_primitive : Any -> (Caught_Panic -> Any) -> Any - catch_primitive ~action handler = @Builtin_Method "Panic.catch_primitive" - - ## PRIVATE - - Returns a raw representation of the stack trace attached to the provided - throwable. It can be a dataflow error, a panic or a native Java exception. - You probably want `Panic.get_attached_stack_trace` instead. - primitive_get_attached_stack_trace : Throwable -> Array - primitive_get_attached_stack_trace throwable = @Builtin_Method "Panic.primitive_get_attached_stack_trace" - -type Caught_Panic - ## A wrapper for a caught panic. - - Arguments: - - payload: the payload carried by the error. - - internal_original_exception (private): the original Java exception that is - the source of this panic. Only for internal use. To get the Java exception - from polyglot exceptions, match the `payload` on `Polyglot_Error` and - extract the Java object from there. - @Builtin_Type - type Caught_Panic payload internal_original_exception - - ## Converts this caught panic into a dataflow error containing the same - payload and stack trace. - convert_to_dataflow_error : Error - convert_to_dataflow_error = @Builtin_Method "Caught_Panic.convert_to_dataflow_error" # Function types. type Function @@ -1293,46 +1110,6 @@ type System @Builtin_Type type System_Process_Result exit_code stdout stderr -## Enso's text type. -type Text - - ## Enso's text type. - - Enso's text type is natively unicode aware, and will handle arbitrary - textual data. - - ? Concatenation - Enso's text type uses a rope-based structure under the hood to provide - users with efficient concatenation operations. - @Builtin_Type - type Text - - ## Concatenates the text that to the right side of this. - - Arguments: - - that: The text to concatenate to this. - - > Example - Concatenating two texts. - - "Hello" + ", world!" - + : Text -> Text - + that = @Builtin_Method "Text.+" - -## Internal text utilities for inspecting text primitives. -type Prim_Text_Helper - - ## PRIVATE - - A container for primitive text operations. - @Builtin_Type - type Prim_Text_Helper - - ## PRIVATE - - Forces flattening of a text value. - optimize : Text - optimize = @Builtin_Method "Prim_Text_Helpers.optimize" ## Utilities for working with threads. type Thread diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index fc2637ede0ba..7a64279c7fd3 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -812,8 +812,8 @@ class IrToTruffle( builtinFalse, branchCodeNode.getCallTarget ) - } else if (atomCons == text.getText) { - TextBranchNode.build(text.getText, branchCodeNode.getCallTarget) + } else if (atomCons == text) { + TextBranchNode.build(text, branchCodeNode.getCallTarget) } else if (atomCons == number.getInteger) { IntegerBranchNode.build(number, branchCodeNode.getCallTarget) } else if (atomCons == number.getDecimal) { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index 32e645ebc80b..79d959ac69f4 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -1,5 +1,6 @@ package org.enso.compiler.codegen +import org.enso.compiler.exception.CompilerError import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.interpreter.runtime.Module import org.enso.interpreter.runtime.builtin.Builtins @@ -25,6 +26,9 @@ class RuntimeStubsGenerator(builtins: Builtins) { localBindings.types.foreach { tp => if (tp.builtinType) { val builtinType = builtins.getBuiltinType(tp.name) + if (builtinType == null) { + throw new CompilerError("Unknown @BuiltinType " + tp.name) + } scope.registerConstructor(builtinType) builtinType.setShadowDefinitions(scope) } else { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index c60050fc353a..7723a4d7f304 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -247,6 +247,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { val code = """ |from Standard.Builtins import all + |from Standard.Base.Error.Common import Panic | |main = | Debug.breakpoint diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index b47643f424f4..ff0d32271018 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -853,12 +853,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(64, 19) - val yId = metadata.addItem(92, 5) - val mainResId = metadata.addItem(102, 12) + val xId = metadata.addItem(60, 19) + val yId = metadata.addItem(88, 5) + val mainResId = metadata.addItem(98, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError | @@ -896,7 +896,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -940,7 +941,9 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + + val responses2 = context.receive(5) + responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), TestMessages.update(contextId, mainResId, Constants.NOTHING), @@ -1191,12 +1194,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(75, 8) - val yId = metadata.addItem(92, 5) - val mainResId = metadata.addItem(102, 12) + val xId = metadata.addItem(71, 8) + val yId = metadata.addItem(88, 5) + val mainResId = metadata.addItem(98, 12) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |foo = | Panic.throw 9 @@ -1235,7 +1238,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + val responses = context.receive(6) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1280,7 +1284,8 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + val responses2 = context.receive(5) + responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( TestMessages.update( contextId, xId, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index d7d934d13da0..8014d5cbd817 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -103,7 +103,7 @@ class RuntimeServerTest } def receive: Option[Api.Response] = { - Option(messageQueue.poll(10, TimeUnit.SECONDS)) + Option(messageQueue.poll(50, TimeUnit.SECONDS)) } def receive(n: Int): List[Api.Response] = { @@ -339,6 +339,13 @@ class RuntimeServerTest val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + "RuntimeServer" should "push and pop functions on the stack" in { val contents = context.Main.code val mainFile = context.writeMain(contents) @@ -1395,12 +1402,13 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(41, 80) - val id1 = metadata.addItem(50, 15) - val id2 = metadata.addItem(70, 18) - val id3 = metadata.addItem(93, 15) + val idMain = metadata.addItem(86, 80) + val id1 = metadata.addItem(95, 15) + val id2 = metadata.addItem(115, 18) + val id3 = metadata.addItem(138, 15) val code = """from Standard.Builtins import all + |from Standard.Base.Data.Text.Text import all | |main = | x = 15.overloaded 1 @@ -1440,7 +1448,8 @@ class RuntimeServerTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + val response = context.receive(7) + response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, idMain, Constants.NOTHING), TestMessages.update( @@ -2796,10 +2805,10 @@ class RuntimeServerTest } it should "return compiler error variable redefined" in { - val contextId = UUID.randomUUID() - val requestId = UUID.randomUUID() + val contextId = UUID.randomUUID() + val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val metadata = new Metadata + val metadata = new Metadata val code = """from Standard.Builtins import all @@ -2866,10 +2875,11 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | x = Panic.catch_primitive @ .convert_to_dataflow_error + | IO.println x | IO.println (x.catch .to_text) |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) @@ -2901,7 +2911,8 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + val response = context.receive(4) + response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2918,7 +2929,8 @@ class RuntimeServerTest context.executionComplete(contextId) ) context.consumeOut shouldEqual List( - "(Error: (Syntax_Error 'Unrecognized token.'))" + "(Error: (Syntax_Error 'Unrecognized token.'))", + "(Syntax_Error 'Unrecognized token.')" ) } @@ -2930,6 +2942,7 @@ class RuntimeServerTest val code = """from Standard.Builtins import all + |from Standard.Base.Error.Common import all | |main = | x = Panic.catch_primitive () .convert_to_dataflow_error @@ -2965,7 +2978,8 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + val response = context.receive(3) + response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2974,7 +2988,7 @@ class RuntimeServerTest Api.ExecutionResult.Diagnostic.error( "Parentheses can't be empty.", Some(mainFile), - Some(model.Range(model.Position(3, 30), model.Position(3, 32))) + Some(model.Range(model.Position(4, 30), model.Position(4, 32))) ) ) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 4ae0691f29e0..d73affd41c0b 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -81,7 +81,7 @@ class RuntimeSuggestionUpdatesTest } def receive: Option[Api.Response] = { - Option(messageQueue.poll(10, TimeUnit.SECONDS)) + Option(messageQueue.poll(50, TimeUnit.SECONDS)) } def receive(n: Int): List[Api.Response] = { @@ -106,6 +106,13 @@ class RuntimeSuggestionUpdatesTest val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + it should "send suggestion updates after file modification" in { val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() @@ -742,6 +749,7 @@ class RuntimeSuggestionUpdatesTest val contents = """from Standard.Builtins import all + |from Standard.Base.Data.Text.Text import all | |main = | x = 15.overloaded 1 @@ -781,7 +789,8 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + val response = context.receive(4) + response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( @@ -836,8 +845,8 @@ class RuntimeSuggestionUpdatesTest "x", Constants.ANY, Suggestion.Scope( - Suggestion.Position(2, 6), - Suggestion.Position(7, 0) + Suggestion.Position(3, 6), + Suggestion.Position(8, 0) ) ), Api.SuggestionAction.Add() diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index c2097f008a78..1aa2cb888db0 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -267,6 +267,13 @@ class RuntimeVisualisationsTest val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + it should "emit visualisation update when expression is computed" in { val idMain = context.Main.metadata.addItem(87, 1) val contents = context.Main.code @@ -1769,10 +1776,10 @@ class RuntimeVisualisationsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(46, 14) + val idMain = metadata.addItem(42, 14) val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = | Panic.throw 42 @@ -1801,7 +1808,8 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(3) should contain theSameElementsAs Seq( + val responses = context.receive(4, timeoutSeconds = 60) + responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index d4d3f968dc5b..57e909c5f873 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala @@ -10,7 +10,7 @@ class CompileDiagnosticsTest extends InterpreterTest { ): Unit = { "surface ast-processing errors in the language" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all | |main = | x = Panic.catch_primitive () .convert_to_dataflow_error @@ -25,7 +25,8 @@ class CompileDiagnosticsTest extends InterpreterTest { "surface parsing errors in the language" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all + |from Standard.Builtins import Nothing | |main = | x = Panic.catch_primitive @ caught_panic-> caught_panic.payload @@ -36,20 +37,22 @@ class CompileDiagnosticsTest extends InterpreterTest { "surface redefinition errors in the language" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all + |from Standard.Builtins import Nothing | |foo = | x = 1 | x = 2 | - |main = Panic.catch_primitive here.foo caught_panic-> caught_panic.payload.to_text + |main = Panic.catch_primitive here.foo caught_panic->caught_panic.payload.to_text |""".stripMargin eval(code) shouldEqual "(Compile_Error 'Variable x is being redefined.')" } "surface non-existent variable errors in the language" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Error.Common import all + |from Standard.Builtins import Nothing | |foo = | my_var = 10 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala index bc252d053421..1f1a2402c9d5 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala @@ -184,5 +184,22 @@ class DataflowErrorsTest extends InterpreterTest { eval(code) consumeOut shouldEqual List("(Error: My_Error)") } + + // TODO: Make sure this is expected + "catch and pretty-print semantic errors" in { + val code = + """from Standard.Base import all + | + |main = + | x = Panic.catch_primitive @ .convert_to_dataflow_error + | IO.println x + | IO.println (x.catch .to_text) + |""".stripMargin + eval(code) + consumeOut shouldEqual List( + "(Error: (Syntax_Error 'Unrecognized token.'))", + "(Syntax_Error 'Unrecognized token.')", + ) + } } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 4dbafb53b698..90281bec9ad4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -58,6 +58,7 @@ class InteropTest extends InterpreterTest { "work with unresolved symbols" in { val code = """from Standard.Builtins import all + |from Standard.Base.Data.Text.Text import all | |Number.add x = x + this |Text.add x = this + x diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PanicsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PanicsTest.scala index 52513e59e69c..d762030376a5 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PanicsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PanicsTest.scala @@ -15,7 +15,7 @@ class PanicsTest extends InterpreterTest { "be thrown and stop evaluation" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type Foo |type Bar @@ -35,7 +35,7 @@ class PanicsTest extends InterpreterTest { "be recoverable and transformed into errors" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |type MyError | @@ -51,7 +51,7 @@ class PanicsTest extends InterpreterTest { "catch polyglot errors" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all |polyglot java import java.lang.Long | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index 183ec8aafeba..98666cedc62a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -91,7 +91,7 @@ class StateTest extends InterpreterTest { "undo changes on Panics" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |panicker = | State.put Number 400 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index 355320e88d07..05863e46170f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -107,6 +107,8 @@ class TextTest extends InterpreterTest { """ |from Standard.Builtins import all |from Standard.Base.Data.List import Cons + |from Standard.Base.Error.Common import all + |from Standard.Base.Data.Text.Text import all | |main = | IO.println (Cons Nothing Nothing).to_display_text diff --git a/test/Tests/src/Data/Noise/Generator_Spec.enso b/test/Tests/src/Data/Noise/Generator_Spec.enso index 2f53d53a1bb5..a617c1cbcd67 100644 --- a/test/Tests/src/Data/Noise/Generator_Spec.enso +++ b/test/Tests/src/Data/Noise/Generator_Spec.enso @@ -1,7 +1,7 @@ from Standard.Base import all import Standard.Base.Data.Noise.Generator -import Standard.Base.Error.Extensions +import Standard.Base.Error.Common import Standard.Test @@ -10,7 +10,7 @@ spec = gen = Generator.Generator Test.specify "should not be invokable" <| interval = Interval.inclusive 0 1 - Test.expect_panic_with (gen.step 1 interval) Extensions.Unimplemented_Error + Test.expect_panic_with (gen.step 1 interval) Common.Unimplemented_Error Test.group "Deterministic Random Noise Generator" <| gen = Generator.Deterministic_Random Test.specify "should always return the same output for the same input" <| From 1a2a80a4c30bc4260664a3ea12a02eb2d6191d79 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 17:48:20 +0200 Subject: [PATCH 25/73] Move IO stuff Adapted a lot of instrumentation tests since they rely on IO.println. Started refactoring some common code in our tests. --- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 + .../interpreter/runtime/builtin/Builtins.java | 11 - .../runtime/src/main/resources/Builtins.enso | 71 ---- .../test/instrument/RuntimeErrorsTest.scala | 152 +++---- .../instrument/RuntimeInstrumentTest.scala | 136 +++---- .../test/instrument/RuntimeServerTest.scala | 375 +++++++++--------- .../RuntimeSuggestionUpdatesTest.scala | 71 ++-- .../test/semantic/CodeLocationsTest.scala | 21 +- .../ComplexTypeDefinitionSugarTest.scala | 2 +- .../test/semantic/DataflowErrorsTest.scala | 19 +- .../interpreter/test/semantic/EvalTest.scala | 3 + .../test/semantic/ExpressionIdTest.scala | 9 +- .../test/semantic/LambdaChainingTest.scala | 2 +- .../test/semantic/LambdaTest.scala | 2 +- .../test/semantic/MethodsTest.scala | 8 +- .../test/semantic/NamedArgumentsTest.scala | 2 +- .../test/semantic/PolyglotTest.scala | 11 +- .../test/semantic/RuntimeManagementTest.scala | 4 + .../interpreter/test/semantic/StateTest.scala | 1 + .../semantic/SuspendedArgumentsTest.scala | 8 +- .../interpreter/test/semantic/TextTest.scala | 13 +- .../scala/org/enso/std/test/BooleanTest.scala | 25 +- .../scala/org/enso/std/test/NumberTest.scala | 2 +- 23 files changed, 397 insertions(+), 555 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 79554a062182..b9481e1d01db 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -20,6 +20,8 @@ import project.Data.Text.Matching import project.Data.Vector import project.Error.Common import project.Error.Extensions +import project.IO.Prim_Io +import project.IO import project.Math import project.Meta import project.Meta.Enso_Project @@ -42,6 +44,8 @@ export project.Data.Ordering export project.Data.Ordering.Sort_Order export project.Data.Ref export project.Data.Vector +export project.IO +export project.IO.Prim_Io export project.Math export project.Meta export project.Polyglot.Java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 671e11aa1e42..f13307325013 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -114,8 +114,6 @@ public Builtins(Context context) { system = new System(language, scope); special = new Special(language); - AtomConstructor io = new AtomConstructor("IO", scope).initializeFields(); - AtomConstructor primIo = new AtomConstructor("Prim_Io", scope).initializeFields(); AtomConstructor runtime = new AtomConstructor("Runtime", scope).initializeFields(); AtomConstructor state = new AtomConstructor("State", scope).initializeFields(); @@ -125,8 +123,6 @@ public Builtins(Context context) { scope.registerConstructor(nothing); scope.registerConstructor(function); - scope.registerConstructor(io); - scope.registerConstructor(primIo); scope.registerConstructor(state); scope.registerConstructor(debug); scope.registerConstructor(projectDescription); @@ -135,13 +131,6 @@ public Builtins(Context context) { scope.registerConstructor(unsafe); - scope.registerMethod(io, "println", PrintlnMethodGen.makeFunction(language)); - scope.registerMethod(io, "print_err", PrintErrMethodGen.makeFunction(language)); - scope.registerMethod(io, "readln", ReadlnMethodGen.makeFunction(language)); - scope.registerMethod(primIo, "get_file", GetFileMethodGen.makeFunction(language)); - scope.registerMethod(primIo, "get_cwd", GetCwdMethodGen.makeFunction(language)); - scope.registerMethod(primIo, "get_user_home", GetUserHomeMethodGen.makeFunction(language)); - scope.registerMethod(runtime, "no_inline", NoInlineMethodGen.makeFunction(language)); scope.registerMethod( runtime, "no_inline_with_arg", NoInlineWithArgMethodGen.makeFunction(language)); diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index b8453dc9857d..0f082d924726 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -103,77 +103,6 @@ type Function call : Any call = @Builtin_Method "Function.call" -## Primitive IO operations internal to the runtime. -type Prim_Io - - ## PRIVATE - - A type for primitive IO operations. - type Prim_Io - - ## PRIVATE - - Gets a file corresponding to the current working directory of the - program. - get_cwd : File - get_cwd = @Builtin_Method "Prim_Io.get_cwd" - - ## PRIVATE - - Gets a file corresponding to the provided path. - - Arguments: - - path: The path to obtain a file at. - get_file : Text -> File - get_file path = @Builtin_Method "Prim_Io.get_file" - - ## PRIVATE - - Gets the textual path to the user's system-defined home directory. - user_home : Text - user_home = @Builtin_Method "Prim_Io.user_home" - -## Built in IO operations. -type IO - - ## A type containing basic operations for performing input and output. - type IO - - ## Prints the provided message to standard error. - - Arguments: - - message: The message to print. It will have to_text called on it to - generate a textual representation that is then printed. - - > Example - Print the message "Oh no!" to standard error. - - IO.print_err "Oh no!" - print_err : Any -> Nothing - print_err message = @Builtin_Method "IO.print_err" - - ## Prints the provided message to standard output. - - Arguments: - - message: The message to print. It will have to_text called on it to - generate a textual representation that is then printed. - - > Example - Print the message "Oh yes!" to standard output. - - IO.println "Oh yes!" - println : Any -> Nothing - println message = @Builtin_Method "IO.println" - - ## Reads a line from standard input. - - > Example - Read a line from standard input. - - IO.readln - readln : Text - readln = @Builtin_Method "IO.readln" - ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index ff0d32271018..ae2f4378bc72 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -19,7 +19,6 @@ import org.scalatest.matchers.should.Matchers import java.io.{ByteArrayOutputStream, File} import java.nio.file.{Files, Path, Paths} import java.util.UUID -import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} @scala.annotation.nowarn("msg=multiarg infix syntax") class RuntimeErrorsTest @@ -37,9 +36,7 @@ class RuntimeErrorsTest var context: TestContext = _ - class TestContext(packageName: String) { - val messageQueue: LinkedBlockingQueue[Api.Response] = - new LinkedBlockingQueue() + class TestContext(packageName: String) extends InstrumentTestContext { val tmpDir: Path = Files.createTempDirectory("enso-test-packages") sys.addShutdownHook(FileSystem.removeDirectoryIfExists(tmpDir)) @@ -97,18 +94,6 @@ class RuntimeErrorsTest def send(msg: Api.Request): Unit = runtimeServerEmulator.sendToRuntime(msg) - def receiveNone: Option[Api.Response] = { - Option(messageQueue.poll()) - } - - def receive: Option[Api.Response] = { - Option(messageQueue.poll(60, TimeUnit.SECONDS)) - } - - def receive(n: Int): List[Api.Response] = { - Iterator.continually(receive).take(n).flatten.toList - } - def consumeOut: List[String] = { val result = out.toString out.reset() @@ -124,14 +109,7 @@ class RuntimeErrorsTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receive - } - - private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { - case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => - false - case _ => - true + val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() } it should "return panic sentinels in method body" in { @@ -157,7 +135,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -181,7 +159,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -241,7 +219,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -265,7 +243,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -320,7 +298,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -344,8 +322,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -364,12 +341,6 @@ class RuntimeErrorsTest ), context.executionComplete(contextId) ) - - val loadedLibraries = responses.collect { - case Api.Response(None, Api.LibraryLoaded(namespace, name, _, _)) => - (namespace, name) - } - loadedLibraries should contain(("Standard", "Base")) } it should "return panic sentinels continuing execution" in { @@ -377,12 +348,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(50, 9) - val yId = metadata.addItem(68, 2) - val mainResId = metadata.addItem(75, 12) + val xId = metadata.addItem(40, 9) + val yId = metadata.addItem(58, 2) + val mainResId = metadata.addItem(65, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | x = undefined @@ -394,7 +365,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -418,7 +389,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -477,7 +448,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -501,8 +472,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(7) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq ( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq ( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -552,7 +522,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -576,8 +546,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -608,8 +577,7 @@ class RuntimeErrorsTest ) ) ) - val responses2 = context.receive(4) - responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), context.executionComplete(contextId) @@ -630,7 +598,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( TestMessages.error( contextId, xId, @@ -661,7 +629,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), context.executionComplete(contextId) @@ -694,7 +662,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -718,8 +686,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -750,7 +717,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("(Error: MyError2)") @@ -785,7 +752,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -809,8 +776,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -842,7 +808,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("(Error: MyError2)") @@ -872,7 +838,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -896,8 +862,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -942,8 +907,7 @@ class RuntimeErrorsTest ) ) - val responses2 = context.receive(5) - responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), TestMessages.update(contextId, mainResId, Constants.NOTHING), @@ -957,12 +921,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(50, 7) - val yId = metadata.addItem(66, 5) - val mainResId = metadata.addItem(76, 12) + val xId = metadata.addItem(49, 7) + val yId = metadata.addItem(65, 5) + val mainResId = metadata.addItem(75, 12) val code = - """from Standard.Builtins import all + """from Standard.Base.IO import all | |main = | x = 1 + foo @@ -974,7 +938,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -998,7 +962,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -1055,7 +1019,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( TestMessages.update(contextId, xId, Constants.INTEGER), TestMessages.update(contextId, yId, Constants.INTEGER), TestMessages.update(contextId, mainResId, Constants.NOTHING), @@ -1090,7 +1054,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1114,8 +1078,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1159,7 +1122,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( TestMessages.panic( contextId, xId, @@ -1214,7 +1177,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1238,8 +1201,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1284,8 +1246,7 @@ class RuntimeErrorsTest ) ) ) - val responses2 = context.receive(5) - responses2.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( TestMessages.update( contextId, xId, @@ -1304,12 +1265,12 @@ class RuntimeErrorsTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(118, 8) - val yId = metadata.addItem(135, 5) - val mainResId = metadata.addItem(145, 12) + val xId = metadata.addItem(108, 8) + val yId = metadata.addItem(125, 5) + val mainResId = metadata.addItem(135, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |foo = @@ -1325,7 +1286,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1349,8 +1310,7 @@ class RuntimeErrorsTest ) ) ) - val responses = context.receive(6) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1386,7 +1346,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( TestMessages.update( contextId, xId, @@ -1408,8 +1368,8 @@ class RuntimeErrorsTest val metadata = new Metadata val xId = metadata.addItem(15, 20) val mainResId = metadata.addItem(40, 1) - val x1Id = metadata.addItem(50, 20) - val mainRes1Id = metadata.addItem(75, 1) + val x1Id = metadata.addItem(40, 20) + val mainRes1Id = metadata.addItem(65, 1) val code = """main = @@ -1421,7 +1381,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1445,7 +1405,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -1488,13 +1448,13 @@ class RuntimeErrorsTest Seq( TextEdit( model.Range(model.Position(0, 0), model.Position(0, 0)), - s"from Standard.Builtins import all$newline$newline" + s"import Standard.Base.IO$newline$newline" ) ) ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( TestMessages.update(contextId, x1Id, Constants.NOTHING), TestMessages.update(contextId, mainRes1Id, Constants.NOTHING), context.executionComplete(contextId) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index f95be531677f..3c8e86069f44 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -17,7 +17,6 @@ import org.scalatest.matchers.should.Matchers import java.io.{ByteArrayOutputStream, File} import java.nio.file.{Files, Path, Paths} import java.util.UUID -import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} @scala.annotation.nowarn("msg=multiarg infix syntax") class RuntimeInstrumentTest @@ -35,10 +34,7 @@ class RuntimeInstrumentTest var context: TestContext = _ - class TestContext(packageName: String) { - val messageQueue: LinkedBlockingQueue[Api.Response] = - new LinkedBlockingQueue() - + class TestContext(packageName: String) extends InstrumentTestContext { val tmpDir: Path = Files.createTempDirectory("enso-test-packages") sys.addShutdownHook(FileSystem.removeDirectoryIfExists(tmpDir)) val lockManager = new ThreadSafeFileLockManager(tmpDir.resolve("locks")) @@ -91,18 +87,6 @@ class RuntimeInstrumentTest def send(msg: Api.Request): Unit = runtimeServerEmulator.sendToRuntime(msg) - def receiveNone: Option[Api.Response] = { - Option(messageQueue.poll()) - } - - def receive: Option[Api.Response] = { - Option(messageQueue.poll(10, TimeUnit.SECONDS)) - } - - def receive(n: Int): List[Api.Response] = { - Iterator.continually(receive).take(n).flatten.toList - } - def consumeOut: List[String] = { val result = out.toString out.reset() @@ -118,7 +102,7 @@ class RuntimeInstrumentTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receive + val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() } it should "instrument simple expression" in { @@ -135,7 +119,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -159,7 +143,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, mainBody, Constants.INTEGER), context.executionComplete(contextId) @@ -184,7 +168,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -208,7 +192,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, mainBody, Constants.TEXT), context.executionComplete(contextId) @@ -237,7 +221,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -261,7 +245,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -279,14 +263,14 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val mainBody = metadata.addItem(41, 52) - val xExpr = metadata.addItem(50, 2) - val yExpr = metadata.addItem(61, 5) - val zExpr = metadata.addItem(75, 1) - val mainResExpr = metadata.addItem(81, 12) + val mainBody = metadata.addItem(31, 52) + val xExpr = metadata.addItem(40, 2) + val yExpr = metadata.addItem(51, 5) + val zExpr = metadata.addItem(65, 1) + val mainResExpr = metadata.addItem(71, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | x = 42 @@ -299,7 +283,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -323,7 +307,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(7) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(7) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xExpr, Constants.INTEGER), TestMessages.update(contextId, yExpr, Constants.INTEGER), @@ -340,14 +324,14 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val mainBody = metadata.addItem(41, 42) - val xExpr = metadata.addItem(50, 2) - val yExpr = metadata.addItem(61, 5) - val mainResExpr = metadata.addItem(71, 12) - val mainRes1Expr = metadata.addItem(82, 1) + val mainBody = metadata.addItem(31, 42) + val xExpr = metadata.addItem(40, 2) + val yExpr = metadata.addItem(51, 5) + val mainResExpr = metadata.addItem(61, 12) + val mainRes1Expr = metadata.addItem(72, 1) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | x = 42 @@ -359,7 +343,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -383,7 +367,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(7) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(7) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xExpr, Constants.INTEGER), TestMessages.update(contextId, yExpr, Constants.INTEGER), @@ -418,7 +402,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -442,7 +426,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, fExpr, Constants.FUNCTION), TestMessages.update(contextId, mainResExpr, Constants.INTEGER), @@ -475,7 +459,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -499,7 +483,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(6) should contain allOf ( + context.receiveN(6) should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, fExpr, Constants.FUNCTION), TestMessages.update(contextId, xExpr, Constants.INTEGER), @@ -534,7 +518,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -558,7 +542,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages .update( @@ -581,13 +565,13 @@ class RuntimeInstrumentTest // f expression metadata.addItem(52, 5) - val aExpr = metadata.addItem(66, 1) - val fApp = metadata.addItem(84, 3) - val mainRes = metadata.addItem(72, 16) - val mainExpr = metadata.addItem(41, 47) + val aExpr = metadata.addItem(56, 1) + val fApp = metadata.addItem(74, 3) + val mainRes = metadata.addItem(62, 16) + val mainExpr = metadata.addItem(31, 47) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | f x = x + 1 @@ -599,7 +583,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -623,7 +607,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, aExpr, Constants.INTEGER), TestMessages.update(contextId, fApp, Constants.INTEGER), @@ -639,16 +623,16 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val aExpr = metadata.addItem(50, 14) + val aExpr = metadata.addItem(40, 14) // lambda - metadata.addItem(51, 10) + metadata.addItem(41, 10) // lambda expression - metadata.addItem(56, 5) - val lamArg = metadata.addItem(63, 1) - val mainRes = metadata.addItem(69, 12) + metadata.addItem(46, 5) + val lamArg = metadata.addItem(53, 1) + val mainRes = metadata.addItem(59, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | a = (x -> x + 1) 1 @@ -659,7 +643,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -683,7 +667,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, aExpr, Constants.INTEGER), TestMessages.update(contextId, lamArg, Constants.INTEGER), @@ -698,14 +682,14 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val aExpr = metadata.addItem(50, 9) + val aExpr = metadata.addItem(40, 9) // lambda - metadata.addItem(51, 5) - val lamArg = metadata.addItem(58, 1) - val mainRes = metadata.addItem(64, 12) + metadata.addItem(41, 5) + val lamArg = metadata.addItem(48, 1) + val mainRes = metadata.addItem(54, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | a = (_ + 1) 1 @@ -716,7 +700,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -740,7 +724,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, aExpr, Constants.INTEGER), TestMessages.update(contextId, lamArg, Constants.INTEGER), @@ -778,7 +762,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -802,7 +786,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xExpr, Constants.THUNK), TestMessages.update(contextId, mainRes, Constants.THUNK), @@ -840,7 +824,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -864,7 +848,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(4) should contain allOf ( + context.receiveN(4) should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xExpr, Constants.THUNK), TestMessages.update(contextId, mainRes, Constants.THUNK), @@ -900,7 +884,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -924,7 +908,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain allOf ( + context.receiveN(5) should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xExpr, Constants.THUNK), TestMessages.update(contextId, mainRes, Constants.THUNK), @@ -972,7 +956,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -996,7 +980,7 @@ class RuntimeInstrumentTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, arg1, Constants.INTEGER), TestMessages.update(contextId, arg2, Constants.INTEGER), diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 8014d5cbd817..0d78d629598d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -20,7 +20,6 @@ import org.scalatest.matchers.should.Matchers import java.io.{ByteArrayOutputStream, File} import java.nio.file.{Files, Path, Paths} import java.util.UUID -import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} @scala.annotation.nowarn("msg=multiarg infix syntax") class RuntimeServerTest @@ -38,9 +37,7 @@ class RuntimeServerTest var context: TestContext = _ - class TestContext(packageName: String) { - val messageQueue: LinkedBlockingQueue[Api.Response] = - new LinkedBlockingQueue() + class TestContext(packageName: String) extends InstrumentTestContext { val tmpDir: Path = Files.createTempDirectory("enso-test-packages") sys.addShutdownHook(FileSystem.removeDirectoryIfExists(tmpDir)) @@ -98,18 +95,6 @@ class RuntimeServerTest def send(msg: Api.Request): Unit = runtimeServerEmulator.sendToRuntime(msg) - def receiveNone: Option[Api.Response] = { - Option(messageQueue.poll()) - } - - def receive: Option[Api.Response] = { - Option(messageQueue.poll(50, TimeUnit.SECONDS)) - } - - def receive(n: Int): List[Api.Response] = { - Iterator.continually(receive).take(n).flatten.toList - } - def consumeOut: List[String] = { val result = out.toString out.reset() @@ -247,12 +232,12 @@ class RuntimeServerTest object Main2 { val metadata = new Metadata - val idMainY = metadata.addItem(183, 10) - val idMainZ = metadata.addItem(202, 10) + val idMainY = metadata.addItem(173, 10) + val idMainZ = metadata.addItem(192, 10) val code = metadata.appendToCode( """ - |from Standard.Builtins import all + |import Standard.Base.IO | |foo = arg -> | IO.println "I'm expensive!" @@ -336,14 +321,7 @@ class RuntimeServerTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receive - } - - private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { - case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => - false - case _ => - true + val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() } "RuntimeServer" should "push and pop functions on the stack" in { @@ -354,7 +332,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -370,7 +348,7 @@ class RuntimeServerTest Api .Request(requestId, Api.PushContextRequest(contextId, invalidLocalItem)) ) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.InvalidStackItemError(contextId)) ) @@ -383,7 +361,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -396,7 +374,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item2)) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.fooY(contextId), context.Main.Update.fooZ(contextId), @@ -415,13 +393,13 @@ class RuntimeServerTest Api.PushContextRequest(contextId, invalidExplicitCall) ) ) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.InvalidStackItemError(contextId)) ) // pop foo call context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), context.Main.Update.mainY(contextId, fromCache = true), context.executionComplete(contextId) @@ -429,13 +407,13 @@ class RuntimeServerTest // pop main context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.PopContextResponse(contextId)) ) // pop empty stack context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.EmptyStackError(contextId)) ) } @@ -446,11 +424,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(58, 24) - val idMainFoo = metadata.addItem(74, 8) + val idMain = metadata.addItem(48, 24) + val idMainFoo = metadata.addItem(64, 8) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |foo a=0 = a + 1 | @@ -462,7 +440,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -486,7 +464,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -506,7 +484,7 @@ class RuntimeServerTest Api.PushContextRequest(contextId, Api.StackItem.LocalCall(idMainFoo)) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) @@ -519,16 +497,17 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(113, 121) - val idMainX = metadata.addItem(140, 8) - val idMainY = metadata.addItem(157, 8) - val idMainM = metadata.addItem(174, 5) - val idMainP = metadata.addItem(188, 5) - val idMainQ = metadata.addItem(202, 5) - val idMainF = metadata.addItem(224, 9) + val idMain = metadata.addItem(137, 121) + val idMainX = metadata.addItem(164, 8) + val idMainY = metadata.addItem(181, 8) + val idMainM = metadata.addItem(198, 5) + val idMainP = metadata.addItem(212, 5) + val idMainQ = metadata.addItem(226, 5) + val idMainF = metadata.addItem(248, 9) val code = """from Standard.Builtins import all + |import Standard.Base.IO |import Enso_Test.Test.A | |type Quux @@ -564,7 +543,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -590,7 +569,7 @@ class RuntimeServerTest ) ) ) - context.receive(9) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(9) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -650,7 +629,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -674,7 +653,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -693,11 +672,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(58, 30) - val idMainFoo = metadata.addItem(75, 12) + val idMain = metadata.addItem(48, 30) + val idMainFoo = metadata.addItem(65, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |foo a b = a + b | @@ -709,7 +688,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -733,7 +712,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -753,11 +732,12 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(42, 41) - val idMainBar = metadata.addItem(74, 8) + val idMain = metadata.addItem(66, 41) + val idMainBar = metadata.addItem(98, 8) val code = """from Standard.Builtins import all + |import Standard.Base.IO | |main = IO.println (State.run Number 42 this.bar) | @@ -768,7 +748,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -792,7 +772,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -812,11 +792,12 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(42, 40) - val idMainBar = metadata.addItem(73, 8) + val idMain = metadata.addItem(66, 40) + val idMainBar = metadata.addItem(97, 8) val code = """from Standard.Builtins import all + |import Standard.Base.IO | |main = IO.println (State.run Number 0 this.bar) | @@ -829,7 +810,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -853,7 +834,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -890,7 +871,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -914,7 +895,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update( contextId, @@ -934,16 +915,16 @@ class RuntimeServerTest val metadata = new Metadata // foo definition - metadata.addItem(35, 22) + metadata.addItem(25, 22) // foo name - metadata.addItem(35, 3) - val fooX = metadata.addItem(49, 1) - val fooRes = metadata.addItem(55, 1) - val mainFoo = metadata.addItem(73, 8) - val mainRes = metadata.addItem(86, 12) + metadata.addItem(25, 3) + val fooX = metadata.addItem(39, 1) + val fooRes = metadata.addItem(45, 1) + val mainFoo = metadata.addItem(63, 8) + val mainRes = metadata.addItem(76, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |foo = | x = 4 @@ -958,7 +939,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -982,7 +963,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages .update( @@ -1003,7 +984,7 @@ class RuntimeServerTest Api.PushContextRequest(contextId, Api.StackItem.LocalCall(mainFoo)) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, fooX, Constants.INTEGER), TestMessages.update(contextId, fooRes, Constants.INTEGER), @@ -1025,14 +1006,14 @@ class RuntimeServerTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("5") // pop the foo call context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages .update( @@ -1056,7 +1037,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1080,7 +1061,7 @@ class RuntimeServerTest ) ) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1094,7 +1075,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item2)) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.fooY(contextId), context.Main.Update.fooZ(contextId), @@ -1103,7 +1084,7 @@ class RuntimeServerTest // pop foo call context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), context.Main.Update.mainY(contextId, fromCache = true), context.executionComplete(contextId) @@ -1111,7 +1092,7 @@ class RuntimeServerTest // pop main context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)) ) } @@ -1122,11 +1103,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idResult = metadata.addItem(55, 4) - val idPrintln = metadata.addItem(64, 17) - val idMain = metadata.addItem(41, 40) + val idResult = metadata.addItem(45, 4) + val idPrintln = metadata.addItem(54, 17) + val idMain = metadata.addItem(31, 40) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | result = 1337 @@ -1137,7 +1118,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1161,7 +1142,7 @@ class RuntimeServerTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, idResult, Constants.INTEGER), TestMessages.update(contextId, idPrintln, Constants.NOTHING), @@ -1184,7 +1165,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( TestMessages.update(contextId, idResult, Constants.TEXT), context.executionComplete(contextId) ) @@ -1197,19 +1178,20 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(41, 35) - val idMainA = metadata.addItem(50, 8) - val idMainP = metadata.addItem(63, 12) + val idMain = metadata.addItem(65, 35) + val idMainA = metadata.addItem(74, 8) + val idMainP = metadata.addItem(87, 12) // pie id - metadata.addItem(75 + 8, 1) + metadata.addItem(99 + 8, 1) // uwu id - metadata.addItem(83 + 8, 1) + metadata.addItem(107 + 8, 1) // hie id - metadata.addItem(91 + 8, 6) + metadata.addItem(115 + 8, 6) // Number.x id - metadata.addItem(111 + 8, 1) + metadata.addItem(135 + 8, 1) val code = """from Standard.Builtins import all + |import Standard.Base.IO | |main = | a = 123 + 21 @@ -1225,7 +1207,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1249,7 +1231,7 @@ class RuntimeServerTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, idMainA, Constants.INTEGER), TestMessages.update(contextId, idMainP, Constants.NOTHING), @@ -1265,14 +1247,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "1234.x 4" ) ) ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, @@ -1290,14 +1272,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "1000.x 5" ) ) ) ) ) - context.receive(1) shouldEqual Seq(context.executionComplete(contextId)) + context.receiveN(1) shouldEqual Seq(context.executionComplete(contextId)) context.consumeOut shouldEqual List("5") // Edit s/1000.x 5/Main.pie/ @@ -1307,14 +1289,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "here.pie" ) ) ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, @@ -1332,14 +1314,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "here.uwu" ) ) ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, @@ -1357,14 +1339,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "here.hie" ) ) ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, @@ -1382,14 +1364,14 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(3, 8), model.Position(3, 16)), + model.Range(model.Position(4, 8), model.Position(4, 16)), "\"Hello!\"" ) ) ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update(contextId, idMainA, Constants.TEXT), context.executionComplete(contextId) ) @@ -1424,7 +1406,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1448,8 +1430,7 @@ class RuntimeServerTest ) ) ) - val response = context.receive(7) - response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, idMain, Constants.NOTHING), TestMessages.update( @@ -1483,14 +1464,14 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) // pop call1 context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages.update( contextId, @@ -1524,14 +1505,14 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) // pop call2 context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages.update( contextId, @@ -1565,14 +1546,14 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) // pop call3 context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages.update( contextId, @@ -1603,11 +1584,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xId = metadata.addItem(50, 10) - val mainRes = metadata.addItem(65, 12) + val xId = metadata.addItem(40, 10) + val mainRes = metadata.addItem(55, 12) val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | x = a -> a + 1 @@ -1618,7 +1599,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1642,7 +1623,7 @@ class RuntimeServerTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, xId, Constants.FUNCTION), TestMessages.update(contextId, mainRes, Constants.NOTHING), @@ -1655,13 +1636,13 @@ class RuntimeServerTest val requestId = UUID.randomUUID() context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) val moduleName = "Enso_Test.Test.Main" val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = IO.println "I'm a file!" |""".stripMargin @@ -1689,7 +1670,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) @@ -1709,7 +1690,7 @@ class RuntimeServerTest ) ) ) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("I'm a modified!") @@ -1728,7 +1709,7 @@ class RuntimeServerTest val code = metadata.appendToCode("main = 84") context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1754,7 +1735,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, idMain, Constants.INTEGER), context.executionComplete(contextId) @@ -1774,7 +1755,7 @@ class RuntimeServerTest ) ) ) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( context.executionComplete(contextId) ) } @@ -1789,7 +1770,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1808,7 +1789,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1822,7 +1803,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item2)) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.fooY(contextId), context.Main.Update.fooZ(contextId), @@ -1831,7 +1812,7 @@ class RuntimeServerTest // pop foo call context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), context.Main.Update.mainY(contextId, fromCache = true), context.executionComplete(contextId) @@ -1839,13 +1820,13 @@ class RuntimeServerTest // pop main context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)) ) // pop empty stack context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.EmptyStackError(contextId)) ) } @@ -1857,12 +1838,13 @@ class RuntimeServerTest val newline = System.lineSeparator() context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) val code = """from Standard.Builtins import all + |import Standard.Base.IO | |main = IO.println "I'm a file!" |""".stripMargin @@ -1890,7 +1872,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.executionComplete(contextId) ) @@ -1899,6 +1881,7 @@ class RuntimeServerTest /* Modify the file: """from Standard.Builtins import all + |import Standard.Base.IO | |Number.lucky = 42 | @@ -1911,18 +1894,18 @@ class RuntimeServerTest mainFile, Seq( TextEdit( - model.Range(model.Position(2, 25), model.Position(2, 29)), + model.Range(model.Position(3, 25), model.Position(3, 29)), "modified" ), TextEdit( - model.Range(model.Position(2, 0), model.Position(2, 0)), + model.Range(model.Position(3, 0), model.Position(3, 0)), s"Number.lucky = 42$newline$newline" ) ) ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("I'm a modified!") @@ -1942,7 +1925,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1961,7 +1944,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1973,7 +1956,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -1988,7 +1971,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2007,7 +1990,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -2025,7 +2008,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -2040,7 +2023,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2059,7 +2042,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -2079,7 +2062,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -2093,7 +2076,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2117,7 +2100,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2137,7 +2120,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2165,7 +2148,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2188,7 +2171,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2216,7 +2199,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2246,7 +2229,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2270,7 +2253,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2314,7 +2297,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2338,7 +2321,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2390,7 +2373,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2414,7 +2397,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2468,7 +2451,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2492,7 +2475,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2537,7 +2520,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2561,7 +2544,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2607,7 +2590,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2631,7 +2614,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2701,7 +2684,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2725,7 +2708,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2762,7 +2745,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2786,7 +2769,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2822,7 +2805,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2846,7 +2829,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2887,7 +2870,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2911,8 +2894,7 @@ class RuntimeServerTest ) ) ) - val response = context.receive(4) - response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2941,7 +2923,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |main = @@ -2954,7 +2936,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2978,8 +2960,7 @@ class RuntimeServerTest ) ) ) - val response = context.receive(3) - response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -3003,7 +2984,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |foo = 1 |foo = 2 @@ -3015,7 +2996,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3039,7 +3020,7 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -3064,7 +3045,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3083,7 +3064,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main2.Update.mainY(contextId), context.Main2.Update.mainZ(contextId), @@ -3095,7 +3076,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -3110,7 +3091,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3140,7 +3121,7 @@ class RuntimeServerTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -3153,7 +3134,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.RenameProject("Enso_Test", "Test", "Foo")) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response(requestId, Api.ProjectRenamed("Enso_Test", "Foo")) ) @@ -3161,7 +3142,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -3176,7 +3157,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), TestMessages.update( contextId, @@ -3189,11 +3170,11 @@ class RuntimeServerTest } it should "send the type graph" in { - val requestId = UUID.randomUUID() + val requestId = UUID.randomUUID() val expectedGraph: TypeGraph = Types.getTypeHierarchy context.send(Api.Request(requestId, Api.GetTypeGraphRequest())) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.GetTypeGraphResponse(expectedGraph)) ) } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index d73affd41c0b..7e6b6d29f851 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -18,7 +18,6 @@ import org.scalatest.matchers.should.Matchers import java.io.{ByteArrayOutputStream, File} import java.nio.file.{Files, Path, Paths} import java.util.UUID -import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} @scala.annotation.nowarn("msg=multiarg infix syntax") class RuntimeSuggestionUpdatesTest @@ -28,9 +27,7 @@ class RuntimeSuggestionUpdatesTest var context: TestContext = _ - class TestContext(packageName: String) { - val messageQueue: LinkedBlockingQueue[Api.Response] = - new LinkedBlockingQueue() + class TestContext(packageName: String) extends InstrumentTestContext { val tmpDir: Path = Files.createTempDirectory("enso-test-packages") sys.addShutdownHook(FileSystem.removeDirectoryIfExists(tmpDir)) @@ -76,18 +73,6 @@ class RuntimeSuggestionUpdatesTest def send(msg: Api.Request): Unit = runtimeServerEmulator.sendToRuntime(msg) - def receiveNone: Option[Api.Response] = { - Option(messageQueue.poll()) - } - - def receive: Option[Api.Response] = { - Option(messageQueue.poll(50, TimeUnit.SECONDS)) - } - - def receive(n: Int): List[Api.Response] = { - Iterator.continually(receive).take(n).flatten.toList - } - def consumeOut: List[String] = { val result = out.toString out.reset() @@ -103,14 +88,7 @@ class RuntimeSuggestionUpdatesTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receive - } - - private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { - case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => - false - case _ => - true + val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() } it should "send suggestion updates after file modification" in { @@ -119,7 +97,7 @@ class RuntimeSuggestionUpdatesTest val moduleName = "Enso_Test.Test.Main" val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") @@ -128,7 +106,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -152,7 +130,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( @@ -222,12 +200,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """from Standard.Base import all | |main = | x = 42 @@ -307,12 +285,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """from Standard.Base import all | |main = | x = 42 @@ -412,12 +390,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """from Standard.Base import all | |main = | x = 42 @@ -526,12 +504,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """from Standard.Base import all | |foo x = x * 10 | @@ -669,12 +647,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """from Standard.Base import all | |foo a b = a * b | @@ -765,7 +743,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -789,8 +767,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - val response = context.receive(4) - response.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( @@ -923,7 +900,7 @@ class RuntimeSuggestionUpdatesTest val moduleName = "Enso_Test.Test.Main" val mainCode = - """from Standard.Builtins import all + """import Standard.Base.IO | |import Enso_Test.Test.A |from Enso_Test.Test.A export all @@ -948,7 +925,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( + context.receiveOne() shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -976,7 +953,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( @@ -1172,12 +1149,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """import Standard.Base.IO | |import Enso_Test.Test.A |from Enso_Test.Test.A export all hiding hello @@ -1216,12 +1193,12 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, version = contentsVersion( - """from Standard.Builtins import all + """import Standard.Base.IO | |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala index dd7e486276ed..7055e775abc3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala @@ -68,18 +68,18 @@ class CodeLocationsTest extends InterpreterTest { withLocationsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |import Standard.Base.IO | |main = | x = 2 + 2 * 2 | y = x * x | IO.println y |""".stripMargin - instrumenter.assertNodeExists(47, 13, classOf[AssignmentNode]) - instrumenter.assertNodeExists(65, 9, classOf[AssignmentNode]) - instrumenter.assertNodeExists(69, 1, classOf[ReadLocalVariableNode]) - instrumenter.assertNodeExists(73, 1, classOf[ReadLocalVariableNode]) - instrumenter.assertNodeExists(90, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(37, 13, classOf[AssignmentNode]) + instrumenter.assertNodeExists(55, 9, classOf[AssignmentNode]) + instrumenter.assertNodeExists(59, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(63, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(80, 1, classOf[ReadLocalVariableNode]) eval(code) () } @@ -89,6 +89,7 @@ class CodeLocationsTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |import Standard.Base.IO | |Nothing.method = | foo = a -> b -> @@ -100,10 +101,10 @@ class CodeLocationsTest extends InterpreterTest { |main = Nothing.method |""".stripMargin - instrumenter.assertNodeExists(118, 5, classOf[ApplicationNode]) - instrumenter.assertNodeExists(136, 1, classOf[ReadLocalVariableNode]) - instrumenter.assertNodeExists(132, 7, classOf[ApplicationNode]) - instrumenter.assertNodeExists(144, 9, classOf[ApplicationNode]) + instrumenter.assertNodeExists(142, 5, classOf[ApplicationNode]) + instrumenter.assertNodeExists(160, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(156, 7, classOf[ApplicationNode]) + instrumenter.assertNodeExists(168, 9, classOf[ApplicationNode]) eval(code) () } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala index 360bd2bb53d8..09313e62ce19 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala @@ -68,7 +68,7 @@ class ComplexTypeDefinitionSugarTest extends InterpreterTest { "work with methods appearing to be suspended blocks" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |type Foo | type Bar diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala index 1f1a2402c9d5..108b2f3cb2ce 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala @@ -13,6 +13,7 @@ class DataflowErrorsTest extends InterpreterTest { val code = """from Standard.Builtins import all |from Standard.Base.Error.Common import all + |import Standard.Base.IO | |type MyError | @@ -32,6 +33,7 @@ class DataflowErrorsTest extends InterpreterTest { val code = """from Standard.Builtins import all |from Standard.Base.Error.Common import all + |import Standard.Base.IO | |type MyError | @@ -63,6 +65,7 @@ class DataflowErrorsTest extends InterpreterTest { val code = """from Standard.Builtins import all |from Standard.Base.Error.Common import all + |import Standard.Base.IO | |type MyCons err | @@ -76,8 +79,8 @@ class DataflowErrorsTest extends InterpreterTest { "accept a method handle in catch function" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Error.Common import all + """from Standard.Base.Error.Common import all + |import Standard.Base.IO | |type MyRecovered x |type MyError x @@ -100,8 +103,8 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through atom construction" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Error.Common import all + """from Standard.Base.Error.Common import all + |import Standard.Base.IO | |type My_Atom a |type My_Error @@ -118,7 +121,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through method resolution" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |type My_Atom @@ -138,7 +141,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through function calls" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |type My_Error @@ -155,7 +158,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through builtin methods" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |type My_Error @@ -171,7 +174,7 @@ class DataflowErrorsTest extends InterpreterTest { "not propagate when explicitly accepted by type and by annotation" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO |from Standard.Base.Error.Common import all | |type My_Error diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala index 1baa0c0766c4..fa2c871f1b5e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala @@ -12,6 +12,7 @@ class EvalTest extends InterpreterTest { "evaluate a string expression" in { val code = s"""from Standard.Builtins import all + |import Standard.Base.IO | |main = | Debug.eval $rawTQ @@ -24,6 +25,7 @@ class EvalTest extends InterpreterTest { "have access to the caller scope" in { val code = s"""from Standard.Builtins import all + |import Standard.Base.IO | |main = | x = "Hello World!" @@ -37,6 +39,7 @@ class EvalTest extends InterpreterTest { "have access to the caller module scope" in { val code = s"""from Standard.Builtins import all + |import Standard.Base.IO | |type MyType x | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala index 4243b5bda552..e155e500a170 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala @@ -56,6 +56,7 @@ class ExpressionIdTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |import Standard.Base.IO | |Nothing.method = | foo = a -> b -> @@ -67,10 +68,10 @@ class ExpressionIdTest extends InterpreterTest { |main = Nothing.method |""".stripMargin val meta = new Metadata - val id1 = meta.addItem(118, 5) - val id2 = meta.addItem(136, 1) - val id3 = meta.addItem(132, 7) - val id4 = meta.addItem(144, 9) + val id1 = meta.addItem(142, 5) + val id2 = meta.addItem(160, 1) + val id3 = meta.addItem(156, 7) + val id4 = meta.addItem(168, 9) instrumenter.assertNodeExists(id1, "30") instrumenter.assertNodeExists(id2, "10") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala index e9840f7a930e..c3e3e4dd68f5 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala @@ -56,7 +56,7 @@ class LambdaChainingTest extends InterpreterTest { "work properly with lazy parameters" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | fn = a -> ~b -> ~c -> diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index 31f410d5b79f..4ce8d5d7cbef 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -117,7 +117,7 @@ class LambdaTest extends InterpreterTest { "call fully saturated returned lambdas" in { val code = - """from Standard.Builtins import all + """from Standard.Base.IO import all | |main = | fn = a -> b -> diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 3b1558819e73..6149460cfde7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala @@ -24,7 +24,8 @@ class MethodsTest extends InterpreterTest { "execute `this` argument once" in { val code = - """from Standard.Builtins import all + """from Standard.Base.IO import all + |from Standard.Builtins import Nothing | |Nothing.foo = 0 | @@ -125,8 +126,9 @@ class MethodsTest extends InterpreterTest { "be callable for any type when defined on Any" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Any import all + """from Standard.Base.Data.Any import all + |from Standard.Base.IO import all + |from Standard.Builtins import Nothing | |type Foo |type Bar diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala index 07cb775a14e4..2ff6016daa9d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala @@ -261,7 +261,7 @@ class NamedArgumentsTest extends InterpreterTest { "work with constructors when no other arguments passed" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.IO | |type My_Tp a=10 b="hello" | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index c6cb47f6e81e..a15643064e4c 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -60,7 +60,7 @@ class PolyglotTest extends InterpreterTest { "match on Polyglot type when imported everything from stdlib" in { val code = """from Standard.Base import all - |from Standard.Builtins import IO, Nothing + |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -77,7 +77,8 @@ class PolyglotTest extends InterpreterTest { "fail to match on Polyglot type when explicitly importing everything from Polyglot module" in { val code = """from Standard.Base.Polyglot import all - |from Standard.Builtins import IO, Nothing + |from Standard.Base.IO import all + |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -94,7 +95,8 @@ class PolyglotTest extends InterpreterTest { "fail to match on Polyglot type case when only importing Polyglot module" in { val code = """import Standard.Base.Polyglot - |from Standard.Builtins import IO, Nothing + |from Standard.Base.IO import all + |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -111,7 +113,8 @@ class PolyglotTest extends InterpreterTest { "match on qualified name of the Polyglot type from Polyglot module" in { val code = """import Standard.Base.Polyglot - |from Standard.Builtins import IO, Nothing + |from Standard.Base.IO import all + |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala index 86083f2f7bff..eeabdd872d38 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala @@ -22,6 +22,7 @@ class RuntimeManagementTest extends InterpreterTest { val code = """from Standard.Builtins import all + |from Standard.Base.IO import all | |foo x = | if x == 0 then IO.println "Start." else Nothing @@ -76,6 +77,7 @@ class RuntimeManagementTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |from Standard.Base.IO import all | |type Mock_File i | @@ -114,6 +116,7 @@ class RuntimeManagementTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |from Standard.Base.IO import all | |type Mock_File i | @@ -153,6 +156,7 @@ class RuntimeManagementTest extends InterpreterTest { val code = """ |from Standard.Builtins import all + |from Standard.Base.IO import all | |type Mock_File i | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index 98666cedc62a..cb12357bb8bd 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -66,6 +66,7 @@ class StateTest extends InterpreterTest { val code = """from Standard.Builtins import all |from Standard.Base.Data.List import Nil + |from Standard.Base.IO import all | |run = | matcher = x -> case x of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala index 2025dfa0422b..c7d21750fcad 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala @@ -23,7 +23,7 @@ class SuspendedArgumentsTest extends InterpreterTest { "not get executed upfront" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | foo = i -> ~x -> ~y -> if i == 0 then x else y @@ -58,7 +58,7 @@ class SuspendedArgumentsTest extends InterpreterTest { "work properly with method dispatch" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |type Foo |type Bar @@ -77,7 +77,7 @@ class SuspendedArgumentsTest extends InterpreterTest { "work properly with oversaturated arguments" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | ifTest = c -> ~ifT -> ~ifF -> if c == 0 then ifT else ifF @@ -92,7 +92,7 @@ class SuspendedArgumentsTest extends InterpreterTest { "work properly with defaulted arguments" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all | |main = a -> (~b = Panic.throw 1) -> a |""".stripMargin diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index 05863e46170f..9d89364e6c94 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -11,7 +11,7 @@ class TextTest extends InterpreterTest { "support text creation with single-line literals" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = IO.println "hello world!" |""".stripMargin @@ -22,7 +22,7 @@ class TextTest extends InterpreterTest { "support text concatenation" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | h = "Hello, " @@ -35,7 +35,7 @@ class TextTest extends InterpreterTest { "support converting arbitrary structures to text" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |type My_Type a | @@ -50,7 +50,7 @@ class TextTest extends InterpreterTest { "support text creation with raw block literals" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO | |main = | x = $rawTQ @@ -68,6 +68,7 @@ class TextTest extends InterpreterTest { "support escape sequences in literals" in { val code = """from Standard.Builtins import all + |import Standard.Base.IO | |main = IO.println '\"Grzegorz Brzeczyszczykiewicz\"' |""".stripMargin @@ -79,6 +80,7 @@ class TextTest extends InterpreterTest { "support printing to standard error" in { val code = s"""from Standard.Builtins import all + |import Standard.Base.IO | |main = IO.print_err "My error string" |""".stripMargin @@ -91,7 +93,7 @@ class TextTest extends InterpreterTest { val inputString = "foobarbaz" val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | IO.readln + " yay!" @@ -109,6 +111,7 @@ class TextTest extends InterpreterTest { |from Standard.Base.Data.List import Cons |from Standard.Base.Error.Common import all |from Standard.Base.Data.Text.Text import all + |import Standard.Base.IO | |main = | IO.println (Cons Nothing Nothing).to_display_text diff --git a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala index d06a02b97c76..3e8bec70eabf 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala @@ -11,8 +11,8 @@ class BooleanTest extends InterpreterTest { "support if_then_else" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all + |from Standard.Base.IO import all | |main = | if True then IO.println "true when true" else IO.println "false when true" @@ -24,8 +24,8 @@ class BooleanTest extends InterpreterTest { "support overriding methods on boolean" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all + |from Standard.Base.IO import all | |Boolean.isTrue = this | @@ -41,8 +41,7 @@ class BooleanTest extends InterpreterTest { "support pattern matching" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all | |to_num b = case b of | True -> 1 @@ -57,8 +56,7 @@ class BooleanTest extends InterpreterTest { "support per-constructor method overloads" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all | |True.to_num = 1 |False.to_num = 2 @@ -70,8 +68,7 @@ class BooleanTest extends InterpreterTest { "support per-single-constructor method overloads" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all | |Boolean.to_num = 2 |True.to_num = 1 @@ -83,8 +80,8 @@ class BooleanTest extends InterpreterTest { "support logical AND and OR operators" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all + |from Standard.Base.IO import all | |main = | IO.println True&&False @@ -99,8 +96,8 @@ class BooleanTest extends InterpreterTest { "support negation" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Boolean import all + """from Standard.Base.Data.Boolean import all + |from Standard.Base.IO import all | |main = | IO.println True.not diff --git a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala index 6887c1c06df5..e73ea1dedb63 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/NumberTest.scala @@ -10,7 +10,7 @@ class NumberTest extends InterpreterTest { ): Unit = { "support equality comparisons" in { val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | IO.println 7==5 From 8e76ba8e487ae225b047de99ddbc595cc3d57892 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 18:23:45 +0200 Subject: [PATCH 26/73] Add missing shared test class --- .../instrument/InstrumentTestContext.scala | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala new file mode 100644 index 000000000000..91bfb21125c5 --- /dev/null +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -0,0 +1,34 @@ +package org.enso.interpreter.test.instrument + +import org.enso.polyglot.runtime.Runtime.Api + +import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} + +class InstrumentTestContext { + protected val messageQueue: LinkedBlockingQueue[Api.Response] = + new LinkedBlockingQueue() + + def receiveNone: Option[Api.Response] = { + Option(messageQueue.poll()) + } + + def receiveOne(timeout: Long=10): Option[Api.Response] = { + Option(messageQueue.poll(timeout, TimeUnit.SECONDS)) + } + + def receiveN(n: Int, timeout: Long=10): List[Api.Response] = { + Iterator.continually(receiveOne(timeout)).take(n).flatten.toList + } + + def receiveNIgnoreStdLib(n: Int): List[Api.Response] = { + receiveN(n+1, 50).filter(excludeLibraryLoadingPayload) + } + + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + +} From d26160860d4b1d0d7334c97fbc305241e39674f1 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 18:54:10 +0200 Subject: [PATCH 27/73] Improve runtime of tests --- .../test/instrument/RuntimeInstrumentTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 8 ++++---- .../instrument/RuntimeSuggestionUpdatesTest.scala | 12 ++++++------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 3c8e86069f44..847141f8041a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -564,7 +564,7 @@ class RuntimeInstrumentTest val metadata = new Metadata // f expression - metadata.addItem(52, 5) + metadata.addItem(42, 5) val aExpr = metadata.addItem(56, 1) val fApp = metadata.addItem(74, 3) val mainRes = metadata.addItem(62, 16) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 0d78d629598d..2eea97f94a03 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -984,7 +984,7 @@ class RuntimeServerTest Api.PushContextRequest(contextId, Api.StackItem.LocalCall(mainFoo)) ) ) - context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.update(contextId, fooX, Constants.INTEGER), TestMessages.update(contextId, fooRes, Constants.INTEGER), @@ -1013,7 +1013,7 @@ class RuntimeServerTest // pop the foo call context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages .update( @@ -1165,7 +1165,7 @@ class RuntimeServerTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update(contextId, idResult, Constants.TEXT), context.executionComplete(contextId) ) @@ -1254,7 +1254,7 @@ class RuntimeServerTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 7e6b6d29f851..c68c2b3a0ca9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -200,7 +200,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, @@ -285,7 +285,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, @@ -390,7 +390,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, @@ -504,7 +504,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, @@ -647,7 +647,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, @@ -1149,7 +1149,7 @@ class RuntimeSuggestionUpdatesTest ) ) ) - context.receiveNIgnoreStdLib(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response( Api.SuggestionsDatabaseModuleUpdateNotification( module = moduleName, From d3e5fa8c3c998dda591a555d2ed40b2c4861ef30 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 18:54:26 +0200 Subject: [PATCH 28/73] Add IO to stdlib Missing from previous commits --- .../lib/Standard/Base/0.0.0-dev/src/IO.enso | 40 +++++++++++++++++++ .../Base/0.0.0-dev/src/IO/Prim_Io.enso | 29 ++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso new file mode 100644 index 000000000000..4313fcb0c937 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso @@ -0,0 +1,40 @@ +## Built in IO operations. +type IO + + ## A type containing basic operations for performing input and output. + type IO + +## Prints the provided message to standard error. + + Arguments: + - message: The message to print. It will have to_text called on it to + generate a textual representation that is then printed. + + > Example + Print the message "Oh no!" to standard error. + + IO.print_err "Oh no!" +print_err : Any -> Nothing +print_err message = @Builtin_Method "IO.print_err" + +## Prints the provided message to standard output. + + Arguments: + - message: The message to print. It will have to_text called on it to + generate a textual representation that is then printed. + + > Example + Print the message "Oh yes!" to standard output. + + IO.println "Oh yes!" +println : Any -> Nothing +println message = @Builtin_Method "IO.println" + +## Reads a line from standard input. + + > Example + Read a line from standard input. + + IO.readln +readln : Text +readln = @Builtin_Method "IO.readln" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso new file mode 100644 index 000000000000..cbb9af002b4b --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso @@ -0,0 +1,29 @@ +## Primitive IO operations internal to the runtime. +type Prim_Io + + ## PRIVATE + + A type for primitive IO operations. + type Prim_Io + +## PRIVATE + + Gets a file corresponding to the current working directory of the + program. +get_cwd : File +get_cwd = @Builtin_Method "Prim_Io.get_cwd" + +## PRIVATE + + Gets a file corresponding to the provided path. + + Arguments: + - path: The path to obtain a file at. +get_file : Text -> File +get_file path = @Builtin_Method "Prim_Io.get_file" + +## PRIVATE + + Gets the textual path to the user's system-defined home directory. +user_home : Text +user_home = @Builtin_Method "Prim_Io.user_home" \ No newline at end of file From 75ba97c45da78f9ecbc909136d90e0c608d48105 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 19:06:46 +0200 Subject: [PATCH 29/73] DRY --- .../instrument/InstrumentTestContext.scala | 12 +- .../test/instrument/RuntimeErrorsTest.scala | 30 ++--- .../instrument/RuntimeInstrumentTest.scala | 32 ++--- .../test/instrument/RuntimeServerTest.scala | 94 +++++++-------- .../RuntimeSuggestionUpdatesTest.scala | 8 +- .../RuntimeVisualisationsTest.scala | 114 +++++++----------- 6 files changed, 133 insertions(+), 157 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala index 91bfb21125c5..308760dffdda 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -12,12 +12,16 @@ class InstrumentTestContext { Option(messageQueue.poll()) } - def receiveOne(timeout: Long=10): Option[Api.Response] = { - Option(messageQueue.poll(timeout, TimeUnit.SECONDS)) + def receive: Option[Api.Response] = { + Option(messageQueue.poll(10, TimeUnit.SECONDS)) } - def receiveN(n: Int, timeout: Long=10): List[Api.Response] = { - Iterator.continually(receiveOne(timeout)).take(n).flatten.toList + def receiveWithTimeout(timeoutSeconds: Long): Option[Api.Response] = { + Option(messageQueue.poll(timeoutSeconds, TimeUnit.SECONDS)) + } + + def receiveN(n: Int, timeoutSeconds: Long=10): List[Api.Response] = { + Iterator.continually(receiveWithTimeout(timeoutSeconds)).take(n).flatten.toList } def receiveNIgnoreStdLib(n: Int): List[Api.Response] = { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index ae2f4378bc72..d8a1815ceb54 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -109,7 +109,7 @@ class RuntimeErrorsTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() + val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } it should "return panic sentinels in method body" in { @@ -135,7 +135,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -219,7 +219,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -298,7 +298,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -365,7 +365,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -448,7 +448,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -522,7 +522,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -662,7 +662,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -752,7 +752,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -838,7 +838,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -938,7 +938,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1054,7 +1054,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1177,7 +1177,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1286,7 +1286,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1381,7 +1381,7 @@ class RuntimeErrorsTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 847141f8041a..b166f9a03111 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -102,7 +102,7 @@ class RuntimeInstrumentTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() + val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } it should "instrument simple expression" in { @@ -119,7 +119,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -168,7 +168,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -221,7 +221,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -283,7 +283,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -343,7 +343,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -402,7 +402,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -459,7 +459,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -518,7 +518,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -583,7 +583,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -643,7 +643,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -700,7 +700,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -762,7 +762,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -824,7 +824,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -884,7 +884,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -956,7 +956,7 @@ class RuntimeInstrumentTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 2eea97f94a03..425c68c4928f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -321,7 +321,7 @@ class RuntimeServerTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() + val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } "RuntimeServer" should "push and pop functions on the stack" in { @@ -332,7 +332,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -348,7 +348,7 @@ class RuntimeServerTest Api .Request(requestId, Api.PushContextRequest(contextId, invalidLocalItem)) ) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.InvalidStackItemError(contextId)) ) @@ -393,7 +393,7 @@ class RuntimeServerTest Api.PushContextRequest(contextId, invalidExplicitCall) ) ) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.InvalidStackItemError(contextId)) ) @@ -407,13 +407,13 @@ class RuntimeServerTest // pop main context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.PopContextResponse(contextId)) ) // pop empty stack context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.EmptyStackError(contextId)) ) } @@ -440,7 +440,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -543,7 +543,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -629,7 +629,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -688,7 +688,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -748,7 +748,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -810,7 +810,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -871,7 +871,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -939,7 +939,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1037,7 +1037,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1118,7 +1118,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1207,7 +1207,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1406,7 +1406,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1599,7 +1599,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1636,7 +1636,7 @@ class RuntimeServerTest val requestId = UUID.randomUUID() context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1690,7 +1690,7 @@ class RuntimeServerTest ) ) ) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( context.executionComplete(contextId) ) context.consumeOut shouldEqual List("I'm a modified!") @@ -1709,7 +1709,7 @@ class RuntimeServerTest val code = metadata.appendToCode("main = 84") context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1755,7 +1755,7 @@ class RuntimeServerTest ) ) ) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( context.executionComplete(contextId) ) } @@ -1770,7 +1770,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1826,7 +1826,7 @@ class RuntimeServerTest // pop empty stack context.send(Api.Request(requestId, Api.PopContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.EmptyStackError(contextId)) ) } @@ -1838,7 +1838,7 @@ class RuntimeServerTest val newline = System.lineSeparator() context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1925,7 +1925,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -1971,7 +1971,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2023,7 +2023,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2076,7 +2076,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2120,7 +2120,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2171,7 +2171,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2229,7 +2229,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2297,7 +2297,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2373,7 +2373,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2451,7 +2451,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2520,7 +2520,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2590,7 +2590,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2684,7 +2684,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2745,7 +2745,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2805,7 +2805,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2870,7 +2870,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2936,7 +2936,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -2996,7 +2996,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3045,7 +3045,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3091,7 +3091,7 @@ class RuntimeServerTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -3174,7 +3174,7 @@ class RuntimeServerTest val expectedGraph: TypeGraph = Types.getTypeHierarchy context.send(Api.Request(requestId, Api.GetTypeGraphRequest())) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.GetTypeGraphResponse(expectedGraph)) ) } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index c68c2b3a0ca9..a20dd2c411ac 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -88,7 +88,7 @@ class RuntimeSuggestionUpdatesTest override protected def beforeEach(): Unit = { context = new TestContext("Test") - val Some(Api.Response(_, Api.InitializedNotification())) = context.receiveOne() + val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } it should "send suggestion updates after file modification" in { @@ -106,7 +106,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -743,7 +743,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) @@ -925,7 +925,7 @@ class RuntimeSuggestionUpdatesTest // create context context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receiveOne() shouldEqual Some( + context.receive shouldEqual Some( Api.Response(requestId, Api.CreateContextResponse(contextId)) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 1aa2cb888db0..710f7d2053fe 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -19,7 +19,6 @@ import org.scalatest.matchers.should.Matchers import java.io.{ByteArrayOutputStream, File} import java.nio.file.{Files, Path, Paths} import java.util.UUID -import java.util.concurrent.{LinkedBlockingQueue, TimeUnit} import scala.io.Source @@ -39,9 +38,7 @@ class RuntimeVisualisationsTest var context: TestContext = _ - class TestContext(packageName: String) { - val messageQueue: LinkedBlockingQueue[Api.Response] = - new LinkedBlockingQueue() + class TestContext(packageName: String) extends InstrumentTestContext { val tmpDir: Path = Files.createTempDirectory("enso-test-packages") sys.addShutdownHook(FileSystem.removeDirectoryIfExists(tmpDir)) @@ -97,23 +94,6 @@ class RuntimeVisualisationsTest def send(msg: Api.Request): Unit = runtimeServerEmulator.sendToRuntime(msg) - def receiveNone: Option[Api.Response] = { - Option(messageQueue.poll()) - } - - def receive: Option[Api.Response] = - receiveTimeout(20) - - def receiveTimeout(timeoutSeconds: Int): Option[Api.Response] = - Option(messageQueue.poll(timeoutSeconds.toLong, TimeUnit.SECONDS)) - - def receive(n: Int, timeoutSeconds: Int = 20): List[Api.Response] = - Iterator - .continually(receiveTimeout(timeoutSeconds)) - .take(n) - .flatten - .toList - def consumeOut: List[String] = { val result = out.toString out.reset() @@ -267,13 +247,6 @@ class RuntimeVisualisationsTest val Some(Api.Response(_, Api.InitializedNotification())) = context.receive } - private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { - case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => - false - case _ => - true - } - it should "emit visualisation update when expression is computed" in { val idMain = context.Main.metadata.addItem(87, 1) val contents = context.Main.code @@ -316,7 +289,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -340,7 +313,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(3) + val attachVisualisationResponses = context.receiveN(3) attachVisualisationResponses should contain allOf ( Api.Response(requestId, Api.VisualisationAttached()), context.executionComplete(contextId) @@ -366,7 +339,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - val recomputeResponses = context.receive(3) + val recomputeResponses = context.receiveN(3) recomputeResponses should contain allOf ( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) @@ -429,7 +402,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -452,7 +425,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -477,7 +450,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - context.receive(2) should contain allOf ( + context.receiveN(2) should contain allOf ( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -494,7 +467,7 @@ class RuntimeVisualisationsTest ) ) ) - val recomputeResponses2 = context.receive(3) + val recomputeResponses2 = context.receiveN(3) recomputeResponses2 should contain allOf ( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) @@ -558,7 +531,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -581,7 +554,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -617,7 +590,7 @@ class RuntimeVisualisationsTest ) ) - val editFileResponse = context.receive(2) + val editFileResponse = context.receiveN(2) editFileResponse should contain( context.executionComplete(contextId) ) @@ -680,7 +653,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -703,7 +676,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -739,7 +712,7 @@ class RuntimeVisualisationsTest ) ) - val editFileResponse = context.receive(2) + val editFileResponse = context.receiveN(2) editFileResponse should contain( context.executionComplete(contextId) ) @@ -800,7 +773,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -824,7 +797,7 @@ class RuntimeVisualisationsTest ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -859,7 +832,7 @@ class RuntimeVisualisationsTest ) ) ) - val modifyVisualisationResponses = context.receive(2) + val modifyVisualisationResponses = context.receiveN(2) modifyVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationModified()) ) @@ -926,7 +899,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.VisualisationAttached()), Api.Response( Api.ExecutionFailed( @@ -946,7 +919,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val pushResponses = context.receive(6) + val pushResponses = context.receiveN(6) pushResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), @@ -991,7 +964,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.RecomputeContextRequest(contextId, None)) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -1008,7 +981,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( + context.receiveN(2) should contain theSameElementsAs Seq( Api.Response(requestId, Api.RecomputeContextResponse(contextId)), context.executionComplete(contextId) ) @@ -1056,7 +1029,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1079,7 +1052,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -1115,7 +1088,7 @@ class RuntimeVisualisationsTest ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) } @@ -1160,7 +1133,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1184,7 +1157,7 @@ class RuntimeVisualisationsTest ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -1230,7 +1203,7 @@ class RuntimeVisualisationsTest ) ) ) - val modifyVisualisationResponses = context.receive(3) + val modifyVisualisationResponses = context.receiveN(3) modifyVisualisationResponses should contain allOf ( Api.Response(requestId, Api.VisualisationModified()), Api.Response(requestId, Api.VisualisationDetached()) @@ -1284,7 +1257,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1308,7 +1281,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response(requestId, Api.ModuleNotFound("Test.Undefined")) ) } @@ -1344,7 +1317,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1370,7 +1343,7 @@ class RuntimeVisualisationsTest ) val attachVisualisationResponses = - context.receive(n = 5, timeoutSeconds = 60) + context.receiveN(n = 5, timeoutSeconds = 60) attachVisualisationResponses should contain allOf ( Api.Response(requestId, Api.VisualisationAttached()), context.executionComplete(contextId) @@ -1432,7 +1405,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1456,7 +1429,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response( requestId, Api.VisualisationExpressionFailed( @@ -1506,7 +1479,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1530,7 +1503,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.VisualisationAttached()), Api.Response( Api.VisualisationEvaluationFailed( @@ -1611,7 +1584,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(6) should contain theSameElementsAs Seq( + context.receiveN(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1635,7 +1608,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.VisualisationAttached()), Api.Response( Api.VisualisationEvaluationFailed( @@ -1714,7 +1687,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val responses = context.receive(n = 4, timeoutSeconds = 60) + val responses = context.receiveN(n = 4, timeoutSeconds = 60) responses should contain allOf( Api.Response(requestId, Api.PushContextResponse(contextId)), @@ -1747,7 +1720,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(3) + val attachVisualisationResponses = context.receiveN(3) attachVisualisationResponses should contain allOf ( Api.Response(requestId, Api.VisualisationAttached()), context.executionComplete(contextId) @@ -1808,8 +1781,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val responses = context.receive(4, timeoutSeconds = 60) - responses.filter(excludeLibraryLoadingPayload) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1834,7 +1806,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.VisualisationAttached()), TestMessages.panic( contextId, @@ -1919,7 +1891,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) val pushContextResponses = - context.receive(n = 5, timeoutSeconds = 90) + context.receiveN(n = 5, timeoutSeconds = 90) pushContextResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( @@ -1950,7 +1922,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(3) + val attachVisualisationResponses = context.receiveN(3) attachVisualisationResponses should contain allOf ( Api.Response(requestId, Api.VisualisationAttached()), context.executionComplete(contextId) From 870aacd5a3d75c5321c7bc1872a01c0e964605a3 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 19:09:19 +0200 Subject: [PATCH 30/73] nit --- .../enso/interpreter/node/expression/builtin/bool/False.java | 2 +- .../org/enso/interpreter/node/expression/builtin/bool/True.java | 2 +- .../interpreter/node/expression/builtin/error/CaughtPanic.java | 2 +- .../node/expression/builtin/text/PrimTextHelper.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java index 7385f68aa1c9..161861a5478b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java @@ -9,4 +9,4 @@ public class False extends AtomConstructor { public False(ModuleScope definitionScope) { super("False", definitionScope, true); } -} \ No newline at end of file +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java index ce808a6a9ec3..5e0f6281318e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java @@ -9,4 +9,4 @@ public class True extends AtomConstructor { public True(ModuleScope definitionScope) { super("True", definitionScope, true); } -} \ No newline at end of file +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 9251c25cf2f9..eeabba9b090c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -9,4 +9,4 @@ public class CaughtPanic extends AtomConstructor { public CaughtPanic(ModuleScope definitionScope) { super("Caught_Panic", definitionScope, true); } -} \ No newline at end of file +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java index 6343eb3232ce..91437d475c22 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java @@ -9,4 +9,4 @@ public class PrimTextHelper extends AtomConstructor { public PrimTextHelper(ModuleScope definitionScope) { super("Prim_Text_Helper", definitionScope, true); } -} \ No newline at end of file +} From 67dafaaefbb62cb995a2f6bc846f877a467daf6f Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 19 Apr 2022 22:25:12 +0200 Subject: [PATCH 31/73] Final AtomConstructor As per PR review, `AtomConstructor` needs to remain final in order to have efficient `instanceof` checks. For now all BuiltinTypes will therefore extend a placeholder class. --- .../node/expression/builtin/Any.java | 8 +-- .../node/expression/builtin/Boolean.java | 8 +-- .../node/expression/builtin/Builtin.java | 8 +++ .../node/expression/builtin/Cons.java | 9 +-- .../node/expression/builtin/Error.java | 8 +-- .../node/expression/builtin/Nil.java | 8 +-- .../node/expression/builtin/Polyglot.java | 9 +-- .../node/expression/builtin/bool/False.java | 9 +-- .../node/expression/builtin/bool/True.java | 9 +-- .../builtin/error/ArithmeticError.java | 10 +-- .../expression/builtin/error/ArityError.java | 10 +-- .../expression/builtin/error/CaughtPanic.java | 9 +-- .../builtin/error/CompileError.java | 10 +-- .../error/InexhaustivePatternMatchError.java | 9 +-- .../builtin/error/InvalidArrayIndexError.java | 9 +-- .../error/InvalidConversionTargetError.java | 9 +-- .../builtin/error/ModuleDoesNotExist.java | 9 +-- .../error/ModuleNotInPackageError.java | 10 +-- .../builtin/error/NoSuchConversionError.java | 10 +-- .../builtin/error/NoSuchMethodError.java | 10 +-- .../builtin/error/NotInvokableError.java | 10 +-- .../node/expression/builtin/error/Panic.java | 9 +-- .../builtin/error/PolyglotError.java | 10 +-- .../expression/builtin/error/SyntaxError.java | 10 +-- .../expression/builtin/error/TypeError.java | 10 +-- .../builtin/error/UninitializedState.java | 10 +-- .../error/UnsupportedArgumentTypes.java | 10 +-- .../expression/builtin/mutable/Array.java | 10 +-- .../node/expression/builtin/mutable/Ref.java | 9 +-- .../builtin/text/PrimTextHelper.java | 9 +-- .../node/expression/builtin/text/Text.java | 9 +-- .../interpreter/runtime/builtin/Builtins.java | 71 ++++++++----------- .../interpreter/runtime/builtin/Error.java | 4 +- .../runtime/callable/atom/Atom.java | 2 +- .../callable/atom/AtomConstructor.java | 2 +- .../enso/interpreter/dsl/TypeProcessor.java | 10 +-- 36 files changed, 103 insertions(+), 273 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java index 27d6cecb37e1..49b55f09190d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -1,12 +1,6 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Any extends AtomConstructor { - public Any(ModuleScope definitionScope) { - super("Any", definitionScope, true); - } -} +public class Any extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java index ac38749fd4dc..d2c95b2d350a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -1,16 +1,10 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; // Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` package along with True and False // because it currently breaks a lot of code generation for builtin methods. // The name Boolean would clash with java.lang.Boolean. // Before moving this definition to the `bool` package, as we should, one would have to address that problem first. @BuiltinType -public class Boolean extends AtomConstructor { - public Boolean(ModuleScope definitionScope) { - super("Boolean", definitionScope, true); - } -} +public class Boolean extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java new file mode 100644 index 000000000000..7e9b55605a7e --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin; + +/** + * A base class for all classes annotated with @BuiltinType. + * Temporarily a placeholder. + */ +public abstract class Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java index 2c9404ca7929..744c3bda3cd2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java @@ -1,13 +1,6 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType(params="head,tail") -public class Cons extends AtomConstructor { - public Cons(ModuleScope definitionScope) { - super("Cons", definitionScope, true); - } -} - +public class Cons extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java index c566ac7284f6..d8c41cf44e76 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java @@ -1,12 +1,6 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Error extends AtomConstructor { - public Error(ModuleScope definitionScope) { - super("Error", definitionScope, true); - } -} \ No newline at end of file +public class Error extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java index 7483946ea2cd..0610cca42b4b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java @@ -1,12 +1,6 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Nil extends AtomConstructor { - public Nil(ModuleScope definitionScope) { - super("Nil", definitionScope, true); - } -} +public class Nil extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java index 6d5142244bd0..1e76617c06db 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java @@ -1,13 +1,6 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; @BuiltinType -public class Polyglot extends AtomConstructor { - public Polyglot(ModuleScope definitionScope) { - super("Polyglot", definitionScope, true); - } -} - +public class Polyglot extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java index 161861a5478b..7860b38b8c0f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.bool; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class False extends AtomConstructor { - public False(ModuleScope definitionScope) { - super("False", definitionScope, true); - } -} +public class False extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java index 5e0f6281318e..9e6b7d3c54fe 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.bool; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class True extends AtomConstructor { - public True(ModuleScope definitionScope) { - super("True", definitionScope, true); - } -} +public class True extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java index 3b7bcb4ef121..51f07586adbd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "message") -public class ArithmeticError extends AtomConstructor { - public ArithmeticError(ModuleScope definitionScope) { - super("Arithmetic_Error", definitionScope, true); - } -} - +public class ArithmeticError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java index a1b4d3ca9108..9491476e24eb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "expected_min,expected_max,actual") -public class ArityError extends AtomConstructor { - public ArityError(ModuleScope definitionScope) { - super("Arity_Error", definitionScope, true); - } -} - +public class ArityError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index eeabba9b090c..031c3a05b761 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params="payload,internal_original_exception") -public class CaughtPanic extends AtomConstructor { - public CaughtPanic(ModuleScope definitionScope) { - super("Caught_Panic", definitionScope, true); - } -} +public class CaughtPanic extends Builtin {} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java index 3bae6f4f1c24..16b001cfd853 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "message") -public class CompileError extends AtomConstructor { - public CompileError(ModuleScope definitionScope) { - super("Compile_Error", definitionScope, true); - } -} - +public class CompileError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java index caea977c7ade..2fa1c28c3312 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -1,13 +1,8 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "scrutinee") -public class InexhaustivePatternMatchError extends AtomConstructor { - public InexhaustivePatternMatchError(ModuleScope definitionScope) { - super("Inexhaustive_Pattern_Match_Error", definitionScope, true); - } -} +public class InexhaustivePatternMatchError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java index f6092cc5191a..b40ab5e91758 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -1,13 +1,8 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "array,index") -public class InvalidArrayIndexError extends AtomConstructor { - public InvalidArrayIndexError(ModuleScope definitionScope) { - super("Invalid_Array_Index_Error", definitionScope, true); - } -} +public class InvalidArrayIndexError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java index 11551ef29aa0..8cc8cc2721ca 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -1,13 +1,8 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "target") -public class InvalidConversionTargetError extends AtomConstructor { - public InvalidConversionTargetError(ModuleScope definitionScope) { - super("Invalid_Conversion_Target_Error", definitionScope, true); - } -} +public class InvalidConversionTargetError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java index 208b3d52374d..43a6c92cfb1c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -1,13 +1,8 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "name") -public class ModuleDoesNotExist extends AtomConstructor { - public ModuleDoesNotExist(ModuleScope definitionScope) { - super("Module_Does_Not_Exist", definitionScope, true); - } -} +public class ModuleDoesNotExist extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java index b24f5b6a15f5..ec8ad7784a37 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class ModuleNotInPackageError extends AtomConstructor { - public ModuleNotInPackageError(ModuleScope definitionScope) { - super("Module_Not_In_Package_Error", definitionScope, true); - } -} - +public class ModuleNotInPackageError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java index 4d88a4d90928..da0c7aacfc0c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "target,that,conversion") -public class NoSuchConversionError extends AtomConstructor { - public NoSuchConversionError(ModuleScope definitionScope) { - super("No_Such_Conversion_Error", definitionScope, true); - } -} - +public class NoSuchConversionError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java index 49139ddf6902..1d1d420863f0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "target,symbol") -public class NoSuchMethodError extends AtomConstructor { - public NoSuchMethodError(ModuleScope definitionScope) { - super("No_Such_Method_Error", definitionScope, true); - } -} - +public class NoSuchMethodError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java index a0ea05797287..40d2fe30fbee 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "target") -public class NotInvokableError extends AtomConstructor { - public NotInvokableError(ModuleScope definitionScope) { - super("Not_Invokable_Error", definitionScope, true); - } -} - +public class NotInvokableError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java index 4bf6c82bc621..b810d421377c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Panic extends AtomConstructor { - public Panic(ModuleScope definitionScope) { - super("Panic", definitionScope, true); - } -} \ No newline at end of file +public class Panic extends Builtin {} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java index ebd16615df44..de651770ce08 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "cause") -public class PolyglotError extends AtomConstructor { - public PolyglotError(ModuleScope definitionScope) { - super("Polyglot_Error", definitionScope, true); - } -} - +public class PolyglotError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java index 0dea752ace3f..c94531789d4b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "message") -public class SyntaxError extends AtomConstructor { - public SyntaxError(ModuleScope definitionScope) { - super("Syntax_Error", definitionScope, true); - } -} - +public class SyntaxError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java index 91d7dcbc8080..e8a59ba758f2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "expected,actual,name") -public class TypeError extends AtomConstructor { - public TypeError(ModuleScope definitionScope) { - super("Type_Error", definitionScope, true); - } -} - +public class TypeError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java index 4d6a4863340c..91a41a90aca9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "key") -public class UninitializedState extends AtomConstructor { - public UninitializedState(ModuleScope definitionScope) { - super("Uninitialized_State", definitionScope, true); - } -} - +public class UninitializedState extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java index 724bd11b8c06..bd8bde436a43 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "arguments") -public class UnsupportedArgumentTypes extends AtomConstructor { - public UnsupportedArgumentTypes(ModuleScope definitionScope) { - super("Unsupported_Argument_Types", definitionScope, true); - } -} - +public class UnsupportedArgumentTypes extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java index b522e51e48ff..f739483ebf34 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java @@ -1,13 +1,7 @@ package org.enso.interpreter.node.expression.builtin.mutable; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Array extends AtomConstructor { - public Array(ModuleScope definitionScope) { - super("Array", definitionScope, true); - } -} - +public class Array extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java index 4cdf59490bb3..273f20e3a418 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.mutable; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Ref extends AtomConstructor { - public Ref(ModuleScope definitionScope) { - super("Ref", definitionScope, true); - } -} +public class Ref extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java index 91437d475c22..27eabf1e0738 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.text; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class PrimTextHelper extends AtomConstructor { - public PrimTextHelper(ModuleScope definitionScope) { - super("Prim_Text_Helper", definitionScope, true); - } -} +public class PrimTextHelper extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java index 4519286370de..3026cb57be86 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java @@ -1,12 +1,7 @@ package org.enso.interpreter.node.expression.builtin.text; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Text extends AtomConstructor { - public Text(ModuleScope definitionScope) { - super("Text", definitionScope, true); - } -} +public class Text extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index f13307325013..4feb7bc05aa2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -18,20 +18,17 @@ import org.enso.interpreter.Language; import org.enso.interpreter.dsl.TypeProcessor; import org.enso.interpreter.dsl.model.MethodDefinition; -import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; +import org.enso.interpreter.node.expression.builtin.*; +import org.enso.interpreter.node.expression.builtin.Boolean; +import org.enso.interpreter.node.expression.builtin.bool.False; +import org.enso.interpreter.node.expression.builtin.bool.True; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; -import org.enso.interpreter.node.expression.builtin.error.CatchPanicMethodGen; -import org.enso.interpreter.node.expression.builtin.error.CaughtPanicConvertToDataflowErrorMethodGen; -import org.enso.interpreter.node.expression.builtin.error.GetAttachedStackTraceMethodGen; -import org.enso.interpreter.node.expression.builtin.error.ThrowPanicMethodGen; +import org.enso.interpreter.node.expression.builtin.error.CaughtPanic; +import org.enso.interpreter.node.expression.builtin.error.Panic; import org.enso.interpreter.node.expression.builtin.function.ExplicitCallFunctionMethodGen; -import org.enso.interpreter.node.expression.builtin.io.GetCwdMethodGen; -import org.enso.interpreter.node.expression.builtin.io.GetFileMethodGen; -import org.enso.interpreter.node.expression.builtin.io.GetUserHomeMethodGen; -import org.enso.interpreter.node.expression.builtin.io.PrintErrMethodGen; -import org.enso.interpreter.node.expression.builtin.io.PrintlnMethodGen; -import org.enso.interpreter.node.expression.builtin.io.ReadlnMethodGen; +import org.enso.interpreter.node.expression.builtin.mutable.Array; +import org.enso.interpreter.node.expression.builtin.mutable.Ref; import org.enso.interpreter.node.expression.builtin.runtime.GCMethodGen; import org.enso.interpreter.node.expression.builtin.runtime.GetStackTraceMethodGen; import org.enso.interpreter.node.expression.builtin.runtime.NoInlineMethodGen; @@ -228,24 +225,18 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { throw new CompilerError("Invalid builtin metadata in: " + line + " " + builtinMeta.length); } - String fullName = builtinMeta[1]; - AtomConstructor builtin = null; - try { - Class clazz = (Class) Class.forName(fullName); - builtin = clazz.getDeclaredConstructor(ModuleScope.class).newInstance(scope); - if (builtinMeta.length == 2) { - builtin = builtin.initializeFields(); - } else { - // there are some type params - String[] paramNames = builtinMeta[2].split(","); - ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; - for (int i = 0; i < paramNames.length; i++) { - args[i] = new ArgumentDefinition(i, paramNames[i], ArgumentDefinition.ExecutionMode.EXECUTE); - } - builtin = builtin.initializeFields(args); + AtomConstructor builtin; + builtin = new AtomConstructor(builtinMeta[0], scope, true); + if (builtinMeta.length == 2) { + builtin = builtin.initializeFields(); + } else { + // there are some type params + String[] paramNames = builtinMeta[2].split(","); + ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; + for (int i = 0; i < paramNames.length; i++) { + args[i] = new ArgumentDefinition(i, paramNames[i], ArgumentDefinition.ExecutionMode.EXECUTE); } - } catch (Exception e) { - e.printStackTrace(); + builtin = builtin.initializeFields(args); } return builtin; }).filter(b -> b != null).collect(Collectors.toList()); @@ -315,7 +306,7 @@ public Optional getBuiltinFunction(AtomConstructor atom, String method } } - public AtomConstructor getBuiltinType(Class clazz) { + public AtomConstructor getBuiltinType(Class clazz) { String snakeCaseName = clazz.getSimpleName().replaceAll("([^_A-Z])([A-Z])", "$1_$2"); return getBuiltinType(snakeCaseName); } @@ -362,17 +353,17 @@ public Number number() { /** @return the Boolean constructor. */ public AtomConstructor bool() { - return builtinTypes.get("Boolean"); + return this.getBuiltinType(Boolean.class); } /** @return the True constructor. */ public AtomConstructor trueAtom() { - return builtinTypes.get("True"); + return this.getBuiltinType(True.class); } /** @return the False constructor. */ public AtomConstructor falseAtom() { - return builtinTypes.get("False"); + return this.getBuiltinType(False.class); } @@ -387,7 +378,7 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - return this.getBuiltinType("Any"); + return this.getBuiltinType(Any.class); } /** @@ -411,27 +402,27 @@ public System system() { /** @return the Array constructor. */ public AtomConstructor array() { - return builtinTypes.get("Array"); + return this.getBuiltinType(Array.class); } /** @return the Ref constructor. */ public AtomConstructor ref() { - return builtinTypes.get("Ref"); + return this.getBuiltinType(Ref.class); } /** @return the container for polyglot-related builtins. */ public AtomConstructor polyglot() { - return builtinTypes.get("Polyglot"); + return this.getBuiltinType(Polyglot.class); } /** @return the {@code Caught_Panic} atom constructor */ public AtomConstructor caughtPanic() { - return builtinTypes.get("Caught_Panic"); + return this.getBuiltinType(CaughtPanic.class); } /** @return the {@code Panic} atom constructor */ public AtomConstructor panic() { - return builtinTypes.get("Panic"); + return this.getBuiltinType(Panic.class); } /** @return the container for ordering-related builtins */ @@ -441,7 +432,7 @@ public Ordering ordering() { /** @return the container for the dataflow error-related builtins */ public AtomConstructor dataflowError() { - return builtinTypes.get("Error"); + return this.getBuiltinType(org.enso.interpreter.node.expression.builtin.Error.class); } public Special special() { @@ -495,7 +486,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.REF: return ref().newInstance(); case Constants.TEXT: - return getBuiltinType(Text.class).newInstance(); + return text().newInstance(); default: return null; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index 5b3900851095..4826c9c42baf 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java @@ -1,5 +1,6 @@ package org.enso.interpreter.runtime.builtin; +import com.oracle.truffle.api.CompilerDirectives; import org.enso.interpreter.node.expression.builtin.error.*; import org.enso.interpreter.node.expression.builtin.error.NoSuchMethodError; import org.enso.interpreter.runtime.callable.UnresolvedConversion; @@ -13,8 +14,9 @@ public class Error { private Builtins builtins; - // FXIME: compilation final + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorDivideByZero; private static final Text shiftTooBigMessage = Text.create("Shift amount too large."); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java index c24916714eae..c39a1c7e4752 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java @@ -26,7 +26,7 @@ /** A runtime representation of an Atom in Enso. */ @ExportLibrary(InteropLibrary.class) @ExportLibrary(MethodDispatchLibrary.class) -public class Atom implements TruffleObject { +public final class Atom implements TruffleObject { final AtomConstructor constructor; private final Object[] fields; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index 3124d0d2a22c..87b81ad207f2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -32,7 +32,7 @@ /** A representation of an Atom constructor. */ @ExportLibrary(InteropLibrary.class) @ExportLibrary(MethodDispatchLibrary.class) -public class AtomConstructor implements TruffleObject { +public final class AtomConstructor implements TruffleObject { private final String name; private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 542bd163a312..dd706ea6f8e8 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -83,11 +83,11 @@ protected boolean handleProcess(Set annotations, RoundEnv } protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { - Map methods = builtinTypes.get(f); - if (methods == null) { - methods = new HashMap<>(); - builtinTypes.put(f, methods); + Map classes = builtinTypes.get(f); + if (classes == null) { + classes = new HashMap<>(); + builtinTypes.put(f, classes); } - methods.put(name, new BuiltinTypeConstr(clazzName, params)); + classes.put(name, new BuiltinTypeConstr(clazzName, params)); } } From f75be8afae3049a0c9c4d784f420ea9f30852d2d Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 20 Apr 2022 17:48:37 +0200 Subject: [PATCH 32/73] Move Nothing and Function to stdlib Nothing is rather present in a number of tests, hence the number of changes. Also discovered a bug in the initialization of shadow definitions. By using the scope from stdlib we were throwing away all synthetic members that get created as part of AtomConstructor initialization, e.g. getters for fields. This became apparent only when trying to remove many builtins imports which were still bringing them into scope. Also, one of `Any` builtin methods wasn't defined on the type, just as a node. Finally, added timings to tests to get a better idead of bottlenecks. --- build.sbt | 1 + .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 10 ++++++ .../Base/0.0.0-dev/src/Data/List.enso | 1 + .../Standard/Base/0.0.0-dev/src/Function.enso | 26 ++++++++++++++ .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 6 +++- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 7 ++++ .../node/expression/builtin/Nothing.java | 6 ++++ .../expression/builtin/function/Function.java | 7 ++++ .../interpreter/runtime/builtin/Builtins.java | 18 +++------- .../callable/atom/AtomConstructor.java | 8 +++++ .../runtime/scope/ModuleScope.java | 6 +++- .../interpreter/runtime/type/Constants.java | 4 +-- .../runtime/src/main/resources/Builtins.enso | 36 ------------------- .../TestNonImportedOverloads/src/Main.enso | 2 +- .../TestNonImportedOverloads/src/Util.enso | 2 +- .../TestNonImportedOwnMethods/src/Main.enso | 2 +- .../TestNonImportedOwnMethods/src/Util.enso | 2 +- .../test/instrument/RuntimeErrorsTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 16 +++++---- .../RuntimeSuggestionUpdatesTest.scala | 9 ++--- .../RuntimeVisualisationsTest.scala | 5 ++- .../test/semantic/CodeLocationsTest.scala | 16 ++++----- .../semantic/CompileDiagnosticsTest.scala | 5 ++- .../test/semantic/ConstructorsTest.scala | 2 +- .../test/semantic/CurryingTest.scala | 2 +- .../test/semantic/DataflowErrorsTest.scala | 6 ++-- .../test/semantic/ExpressionIdTest.scala | 10 +++--- .../test/semantic/FunctionSugarTest.scala | 2 +- .../test/semantic/GlobalScopeTest.scala | 10 +++--- .../test/semantic/LambdaTest.scala | 2 +- .../test/semantic/MethodsTest.scala | 4 +-- .../test/semantic/NamedArgumentsTest.scala | 24 ++++++------- .../OverloadsResolutionErrorTest.scala | 2 +- .../test/semantic/RuntimeManagementTest.scala | 3 ++ .../interpreter/test/semantic/StateTest.scala | 5 +-- .../interpreter/test/semantic/TextTest.scala | 5 ++- 36 files changed, 155 insertions(+), 119 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java diff --git a/build.sbt b/build.sbt index b4d2cf0d7027..92e090648f44 100644 --- a/build.sbt +++ b/build.sbt @@ -1130,6 +1130,7 @@ lazy val runtime = (project in file("engine/runtime")) inConfig(Benchmark)(Defaults.testSettings), Test / parallelExecution := false, Test / logBuffered := false, + Test / testOptions += Tests.Argument("-oD"), // show timings for individual tests scalacOptions += "-Ymacro-annotations", scalacOptions ++= Seq("-Ypatmat-exhaust-depth", "off"), libraryDependencies ++= jmh ++ jaxb ++ circe ++ Seq( diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index 5c63cab5c8c6..b41e85165333 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -30,6 +30,16 @@ type Any to_text : Text to_text = @Builtin_Method "Any.to_text" + ## Generic conversion of an arbitrary Enso value to a corresponding human-readable + representation. + + > Example + Getting a human-readable textual representation of the number 7. + + 7.to_text + to_display_text : Text + to_display_text = @Builtin_Method "Any.to_display_text" + ## ALIAS Equality Checks if `this` is equal to `that`. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 6fbe8c908a12..b1ef02952e16 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,6 +1,7 @@ from Standard.Builtins import all from Standard.Base.Error.Common import Error from Standard.Base.Data.Boolean import True, False +import Standard.Base.Nothing ## The basic cons-list type. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso new file mode 100644 index 000000000000..e37d86b227ed --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso @@ -0,0 +1,26 @@ +# Function types. +type Function + + ## A function is any type that represents a not-yet evaluated computation. + + Methods are represented as functions with dynamic dispatch semantics on + the this argument. + @Builtin_Type + type Function + + ## Forces evaluation of a fully-applied but not evaluated function. + + This is particularly useful when you want to call a function that is + fully applied with default arguments. + + This is usually _not_ the correct solution to a problem, and so should be + used sparingly. + + > Example + Evaluate a fully applied function to get 4. + + example_call = + f (a = 2) = a * a + f.call + call : Any + call = @Builtin_Method "Function.call" \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index b9481e1d01db..c109f2efaec3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -20,8 +20,10 @@ import project.Data.Text.Matching import project.Data.Vector import project.Error.Common import project.Error.Extensions +import project.Function import project.IO.Prim_Io import project.IO +import project.Nothing import project.Math import project.Meta import project.Meta.Enso_Project @@ -33,7 +35,7 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Nothing, Number, Integer +from Standard.Builtins import Number, Integer export project.Data.Interval export project.Data.Json @@ -74,7 +76,9 @@ from project.Data.Text.Matching export Case_Insensitive, Text_Matcher, Regex_Mat from project.Data.Text.Text export all from project.Error.Common export all from project.Error.Extensions export all +from project.Function export all from project.Meta.Enso_Project export all +from project.Nothing export all from project.Polyglot export all from project.Runtime.Extensions export all diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso new file mode 100644 index 000000000000..f2d7a0715de7 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso @@ -0,0 +1,7 @@ +## The type that has only a singleton value. + + It is often used alongside a value of type a to provide a Maybe or + Option abstraction. The type a | Nothing is semantically equivalent to + Maybe a. +@Builtin_Type +type Nothing \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java new file mode 100644 index 000000000000..54b9987be13d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java @@ -0,0 +1,6 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +public class Nothing extends Builtin {} \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java new file mode 100644 index 000000000000..2003ce43079f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.function; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class Function extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 4feb7bc05aa2..a4bf298a1825 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -70,8 +70,6 @@ public static class Debug { private final AtomConstructor debug; private final AtomConstructor projectDescription; - private final AtomConstructor function; - private final AtomConstructor nothing; private final Error error; private final Module module; @@ -103,8 +101,6 @@ public Builtins(Context context) { 0, "prim_root_file", ArgumentDefinition.ExecutionMode.EXECUTE), new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); error = new Error(this); - function = new AtomConstructor("Function", scope).initializeFields(); - nothing = new AtomConstructor("Nothing", scope).initializeFields(); number = new Number(language, scope); ordering = new Ordering(language, scope); resource = new Resource(language, scope); @@ -117,8 +113,6 @@ public Builtins(Context context) { AtomConstructor thread = new AtomConstructor("Thread", scope).initializeFields(); AtomConstructor unsafe = new AtomConstructor("Unsafe", scope).initializeFields(); - scope.registerConstructor(nothing); - scope.registerConstructor(function); scope.registerConstructor(state); scope.registerConstructor(debug); @@ -142,7 +136,6 @@ public Builtins(Context context) { scope.registerMethod(debug, MethodNames.Debug.EVAL, DebugEvalMethodGen.makeFunction(language)); scope.registerMethod(debug, "breakpoint", DebugBreakpointMethodGen.makeFunction(language)); - scope.registerMethod(function, "call", ExplicitCallFunctionMethodGen.makeFunction(language)); scope.registerMethod( thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); @@ -241,8 +234,7 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { return builtin; }).filter(b -> b != null).collect(Collectors.toList()); } - - + private void readBuiltinsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; @@ -321,7 +313,7 @@ public AtomConstructor getBuiltinType(String name) { * @return the {@code Nothing} atom constructor */ public AtomConstructor nothing() { - return nothing; + return getBuiltinType(Nothing.class); } /** @@ -339,7 +331,7 @@ public AtomConstructor text() { * @return the {@code Function} atom constructor */ public AtomConstructor function() { - return function; + return getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); } /** @@ -472,13 +464,13 @@ public Atom fromTypeSystem(String typeName) { case Constants.ERROR: return dataflowError().newInstance(); case Constants.FUNCTION: - return function.newInstance(); + return function().newInstance(); case Constants.INTEGER: return number.getInteger().newInstance(); case Constants.MANAGED_RESOURCE: return resource.getManagedResource().newInstance(); case Constants.NOTHING: - return nothing.newInstance(); + return nothing().newInstance(); case Constants.NUMBER: return number.getNumber().newInstance(); case Constants.PANIC: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index 87b81ad207f2..e6855c3d1d0a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -29,6 +29,8 @@ import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.pkg.QualifiedName; +import java.util.Map; + /** A representation of an Atom constructor. */ @ExportLibrary(InteropLibrary.class) @ExportLibrary(MethodDispatchLibrary.class) @@ -67,6 +69,12 @@ public boolean isBuiltin() { public void setShadowDefinitions(ModuleScope scope) { if (builtin) { + // Ensure that synthetic methods, such as getters for fields are in the scope + // Some scopes won't have any methods at this point, e.g., Nil or Nothing, hence the null check. + Map methods = this.definitionScope.getMethods().get(this); + if (methods != null) { + methods.forEach((name, fun) -> scope.registerMethod(this, name, fun)); + } this.definitionScope = scope; } else { throw new RuntimeException("Attempting to modify scope of a non-builtin type post-construction is not allowed"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 41a20129a655..8a4fab360279 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -116,7 +116,11 @@ public void registerMethod(AtomConstructor atom, String method, Function functio Map methodMap = ensureMethodMapFor(atom); if (methodMap.containsKey(method)) { - throw new RedefinedMethodException(atom.getName(), method); + if (!atom.isBuiltin()) { + // Builtin types will have double definition because of + // BuiltinMethod and that's OK + throw new RedefinedMethodException(atom.getName(), method); + } } else { methodMap.put(method, function); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 47176e0d2501..c863cfcc20ec 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -8,11 +8,11 @@ public class Constants { public static final String BOOLEAN = "Standard.Builtins.Main.Boolean"; public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; public static final String ERROR = "Standard.Base.Error.Common.Error"; - public static final String FUNCTION = "Standard.Builtins.Main.Function"; + public static final String FUNCTION = "Standard.Base.Function.Function"; public static final String INTEGER = "Standard.Builtins.Main.Integer"; public static final String MANAGED_RESOURCE = "Standard.Builtins.Main.Managed_Resource"; public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; - public static final String NOTHING = "Standard.Builtins.Main.Nothing"; + public static final String NOTHING = "Standard.Base.Nothing.Nothing"; public static final String NUMBER = "Standard.Builtins.Main.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 0f082d924726..4ab9a726e10f 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -75,34 +75,6 @@ type Prim_Warning get_reassignments : Prim_Warning -> Any get_reassignments warn = @Builtin_Method "Prim_Warning.get_reassignments" - -# Function types. -type Function - - ## A function is any type that represents a not-yet evaluated computation. - - Methods are represented as functions with dynamic dispatch semantics on - the this argument. - @Builtin_Type - type Function - - ## Forces evaluation of a fully-applied but not evaluated function. - - This is particularly useful when you want to call a function that is - fully applied with default arguments. - - This is usually _not_ the correct solution to a problem, and so should be - used sparingly. - - > Example - Evaluate a fully applied function to get 4. - - example_call = - f (a = 2) = a * a - f.call - call : Any - call = @Builtin_Method "Function.call" - ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or @@ -1096,14 +1068,6 @@ type Project_Description @Builtin_Type type Project_Description prim_root_file -## The type that has only a singleton value. - - It is often used alongside a value of type a to provide a Maybe or - Option abstraction. The type a | Nothing is semantically equivalent to - Maybe a. -@Builtin_Type -type Nothing - ## A representation of the relative ordering between two values. type Ordering diff --git a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso index df6fe3124123..0ffaf89e0a3c 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso @@ -1,4 +1,4 @@ -from Standard.Builtins import all +import Standard.Base.Nothing from local.TestNonImportedOverloads.Util import all X.method = 10 diff --git a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso index fc2410fefef4..e717ae274a19 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso @@ -1,4 +1,4 @@ -from Standard.Builtins import all +import Standard.Base.Nothing type X a diff --git a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso index b8a9ebda5d20..d63614273be9 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso @@ -1,4 +1,4 @@ -from Standard.Builtins import all +import Standard.Base.Nothing import local.TestNonImportedOwnMethods.Util type X a diff --git a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Util.enso b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Util.enso index dc1d88759a6b..2c485956ef44 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Util.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Util.enso @@ -1,3 +1,3 @@ -from Standard.Builtins import all +import Standard.Base.Nothing Nothing.util = x -> x.method diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index d8a1815ceb54..5bf5e9b79472 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -1246,7 +1246,7 @@ class RuntimeErrorsTest ) ) ) - context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( TestMessages.update( contextId, xId, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 425c68c4928f..0f72b5443001 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -1384,19 +1384,23 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(86, 80) - val id1 = metadata.addItem(95, 15) - val id2 = metadata.addItem(115, 18) - val id3 = metadata.addItem(138, 15) + val idMain = metadata.addItem(118, 88) + val id1 = metadata.addItem(127, 15) + val id2 = metadata.addItem(147, 18) + val id3 = metadata.addItem(170, 15) + // Note that Nothing.Nothing is on purpose. + // If not provided the full name it will resolve the + // expression type of Nothing to a Nothing module val code = - """from Standard.Builtins import all + """from Standard.Builtins import Number |from Standard.Base.Data.Text.Text import all + |import Standard.Base.Nothing | |main = | x = 15.overloaded 1 | "foo".overloaded 2 | 10.overloaded x - | Nothing + | Nothing.Nothing | |Text.overloaded arg = arg + 1 |Number.overloaded arg = arg + 2 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index a20dd2c411ac..90a07bae6d89 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -726,8 +726,9 @@ class RuntimeSuggestionUpdatesTest val moduleName = "Enso_Test.Test.Main" val contents = - """from Standard.Builtins import all + """from Standard.Builtins import Number |from Standard.Base.Data.Text.Text import all + |import Standard.Base.Nothing | |main = | x = 15.overloaded 1 @@ -822,8 +823,8 @@ class RuntimeSuggestionUpdatesTest "x", Constants.ANY, Suggestion.Scope( - Suggestion.Position(3, 6), - Suggestion.Position(8, 0) + Suggestion.Position(4, 6), + Suggestion.Position(9, 0) ) ), Api.SuggestionAction.Add() @@ -908,7 +909,7 @@ class RuntimeSuggestionUpdatesTest |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") val aCode = - """from Standard.Builtins import all + """from Standard.Builtins import Integer | |type MyType | type MkA a diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 710f7d2053fe..7737dcbc81dc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -1851,11 +1851,10 @@ class RuntimeVisualisationsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(120, 28) + val idMain = metadata.addItem(86, 28) val code = - """from Standard.Builtins import all - |import Standard.Base.Data.List + """import Standard.Base.Data.List |from Standard.Base.Error.Common import all | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala index 7055e775abc3..478665748fc3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala @@ -54,12 +54,12 @@ class CodeLocationsTest extends InterpreterTest { "be correct in applications and method calls" in withLocationsInstrumenter { instrumenter => val code = - """from Standard.Base import all + """from Standard.Base.Data.List import Cons | |main = (2-2 == 0).if_then_else (Cons 5 6) 0 |""".stripMargin - instrumenter.assertNodeExists(38, 36, classOf[ApplicationNode]) - instrumenter.assertNodeExists(63, 8, classOf[ApplicationNode]) + instrumenter.assertNodeExists(49, 36, classOf[ApplicationNode]) + instrumenter.assertNodeExists(74, 8, classOf[ApplicationNode]) eval(code) () } @@ -88,7 +88,7 @@ class CodeLocationsTest extends InterpreterTest { withLocationsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |import Standard.Base.Nothing |import Standard.Base.IO | |Nothing.method = @@ -101,10 +101,10 @@ class CodeLocationsTest extends InterpreterTest { |main = Nothing.method |""".stripMargin - instrumenter.assertNodeExists(142, 5, classOf[ApplicationNode]) - instrumenter.assertNodeExists(160, 1, classOf[ReadLocalVariableNode]) - instrumenter.assertNodeExists(156, 7, classOf[ApplicationNode]) - instrumenter.assertNodeExists(168, 9, classOf[ApplicationNode]) + instrumenter.assertNodeExists(137, 5, classOf[ApplicationNode]) + instrumenter.assertNodeExists(155, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(151, 7, classOf[ApplicationNode]) + instrumenter.assertNodeExists(163, 9, classOf[ApplicationNode]) eval(code) () } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index 57e909c5f873..175bbfc4900e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala @@ -8,7 +8,7 @@ class CompileDiagnosticsTest extends InterpreterTest { override def specify(implicit interpreterContext: InterpreterContext ): Unit = { - "surface ast-processing errors in the language" in { + "surface ast-processing errors in the language" in { val code = """from Standard.Base.Error.Common import all | @@ -26,7 +26,6 @@ class CompileDiagnosticsTest extends InterpreterTest { "surface parsing errors in the language" in { val code = """from Standard.Base.Error.Common import all - |from Standard.Builtins import Nothing | |main = | x = Panic.catch_primitive @ caught_panic-> caught_panic.payload @@ -35,7 +34,7 @@ class CompileDiagnosticsTest extends InterpreterTest { eval(code) shouldEqual "(Syntax_Error 'Unrecognized token.')" } - "surface redefinition errors in the language" in { + "surface redefinition errors in the language" in { val code = """from Standard.Base.Error.Common import all |from Standard.Builtins import Nothing diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index 09faf2a962e3..53a805c38fa0 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala @@ -85,7 +85,7 @@ class ConstructorsTest extends InterpreterTest { "be usable in code, with arbitrary definition order" in { val testCode = - """from Standard.Builtins import all + """import Standard.Base.Nothing |from Standard.Base.Data.List import all | |type Cons2 a b diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala index 5c369ee00abb..4309db162acc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala @@ -66,7 +66,7 @@ class CurryingTest extends InterpreterTest { "allow default arguments to be suspended in method call syntax" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.fn = w -> x -> (y = 10) -> (z = 20) -> w + x + y + z | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala index 108b2f3cb2ce..4e7539f13bab 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala @@ -11,7 +11,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through pattern matches" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing |from Standard.Base.Error.Common import all |import Standard.Base.IO | @@ -31,7 +31,7 @@ class DataflowErrorsTest extends InterpreterTest { "propagate through specialized pattern matches" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing |from Standard.Base.Error.Common import all |import Standard.Base.IO | @@ -63,7 +63,7 @@ class DataflowErrorsTest extends InterpreterTest { "accept a constructor handler in catch function" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing |from Standard.Base.Error.Common import all |import Standard.Base.IO | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala index e155e500a170..469b1543c51f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala @@ -55,7 +55,7 @@ class ExpressionIdTest extends InterpreterTest { withIdsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |import Standard.Base.Nothing |import Standard.Base.IO | |Nothing.method = @@ -68,10 +68,10 @@ class ExpressionIdTest extends InterpreterTest { |main = Nothing.method |""".stripMargin val meta = new Metadata - val id1 = meta.addItem(142, 5) - val id2 = meta.addItem(160, 1) - val id3 = meta.addItem(156, 7) - val id4 = meta.addItem(168, 9) + val id1 = meta.addItem(137, 5) + val id2 = meta.addItem(155, 1) + val id3 = meta.addItem(151, 7) + val id4 = meta.addItem(163, 9) instrumenter.assertNodeExists(id1, "30") instrumenter.assertNodeExists(id2, "10") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala index deff629c32ab..8db28950437a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala @@ -22,7 +22,7 @@ class FunctionSugarTest extends InterpreterTest { "work for methods" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.foo a b = a * b - a | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala index 4da75318f52f..1c6e740532c4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala @@ -12,7 +12,7 @@ class GlobalScopeTest extends InterpreterTest { "use values from the global scope in their bodies" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.a = 10 |Nothing.add_ten = b -> Nothing.a + b @@ -25,7 +25,7 @@ class GlobalScopeTest extends InterpreterTest { "be able to call other functions in scope" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.adder = a -> b -> a + b | @@ -42,7 +42,7 @@ class GlobalScopeTest extends InterpreterTest { "be able to be passed as values when in scope" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.adder = a -> b -> a + b | @@ -58,7 +58,7 @@ class GlobalScopeTest extends InterpreterTest { "be able to mutually recurse in the global scope" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.decrementCall = number -> | res = number - 1 @@ -75,7 +75,7 @@ class GlobalScopeTest extends InterpreterTest { "be suspended within blocks" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.a = 10/0 | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index 4ce8d5d7cbef..6b85b4638246 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -89,7 +89,7 @@ class LambdaTest extends InterpreterTest { "support the use of oversaturated args in methods" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.my_method = 1 | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 6149460cfde7..20d663b1b22a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala @@ -25,7 +25,7 @@ class MethodsTest extends InterpreterTest { "execute `this` argument once" in { val code = """from Standard.Base.IO import all - |from Standard.Builtins import Nothing + |import Standard.Base.Nothing | |Nothing.foo = 0 | @@ -128,7 +128,7 @@ class MethodsTest extends InterpreterTest { val code = """from Standard.Base.Data.Any import all |from Standard.Base.IO import all - |from Standard.Builtins import Nothing + |import Standard.Base.Nothing | |type Foo |type Bar diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala index 2ff6016daa9d..23b25a91ea48 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala @@ -15,7 +15,7 @@ class NamedArgumentsTest extends InterpreterTest { "be used in function bodies" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.a = 10 |Nothing.add_ten = b -> Nothing.a + b @@ -28,7 +28,7 @@ class NamedArgumentsTest extends InterpreterTest { "be passed when given out of order" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.subtract = a -> b -> a - b | @@ -53,7 +53,7 @@ class NamedArgumentsTest extends InterpreterTest { "be definable" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.add_num = a -> (num = 10) -> a + num | @@ -65,7 +65,7 @@ class NamedArgumentsTest extends InterpreterTest { "be able to default to complex expressions" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.add = a -> b -> a + b |Nothing.do_thing = a -> (b = Nothing.add 1 2) -> a + b @@ -91,7 +91,7 @@ class NamedArgumentsTest extends InterpreterTest { "be used in functions when no arguments are supplied" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.add_together = (a = 5) -> (b = 6) -> a + b | @@ -103,7 +103,7 @@ class NamedArgumentsTest extends InterpreterTest { "be overridable by name" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.add_num = a -> (num = 10) -> a + num | @@ -115,7 +115,7 @@ class NamedArgumentsTest extends InterpreterTest { "overridable by position" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.add_num = a -> (num = 10) -> a + num | @@ -127,7 +127,7 @@ class NamedArgumentsTest extends InterpreterTest { "work in a recursive context" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.summer = sumTo -> | summator = (acc = 0) -> current -> @@ -158,7 +158,7 @@ class NamedArgumentsTest extends InterpreterTest { "be applied in a sequence compatible with Eta-expansions" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.foo = a -> b -> c -> a -> a |main = Nothing.foo 20 (a = 10) 0 0 @@ -169,7 +169,7 @@ class NamedArgumentsTest extends InterpreterTest { "be able to depend on prior arguments" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.double_or_add = a -> (b = a) -> a + b | @@ -181,7 +181,7 @@ class NamedArgumentsTest extends InterpreterTest { "not be able to depend on later arguments" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.bad_arg_fn = a -> (b = c) -> (c = a) -> a + b + c | @@ -243,7 +243,7 @@ class NamedArgumentsTest extends InterpreterTest { "work with constructors" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |type Cons2 head (rest = Nil2) |type Nil2 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala index 55f7625401a2..e637f87985b2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala @@ -20,7 +20,7 @@ class OverloadsResolutionErrorTest extends InterpreterTest { "result in an error at runtime for method overloads" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Nothing | |Nothing.foo = 10 |Nothing.foo = 20 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala index eeabdd872d38..47cf1fc6f1a9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala @@ -23,6 +23,7 @@ class RuntimeManagementTest extends InterpreterTest { val code = """from Standard.Builtins import all |from Standard.Base.IO import all + |import Standard.Base.Nothing | |foo x = | if x == 0 then IO.println "Start." else Nothing @@ -117,6 +118,7 @@ class RuntimeManagementTest extends InterpreterTest { """ |from Standard.Builtins import all |from Standard.Base.IO import all + |import Standard.Base.Nothing | |type Mock_File i | @@ -157,6 +159,7 @@ class RuntimeManagementTest extends InterpreterTest { """ |from Standard.Builtins import all |from Standard.Base.IO import all + |import Standard.Base.Nothing | |type Mock_File i | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index cb12357bb8bd..a9dc4ffb6706 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -64,9 +64,10 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Builtins import all + """from Standard.Builtins import State,Number |from Standard.Base.Data.List import Nil - |from Standard.Base.IO import all + |import Standard.Base.IO + |import Standard.Base.Nothing | |run = | matcher = x -> case x of diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index 9d89364e6c94..d824aa8df199 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -67,8 +67,7 @@ class TextTest extends InterpreterTest { "support escape sequences in literals" in { val code = - """from Standard.Builtins import all - |import Standard.Base.IO + """import Standard.Base.IO | |main = IO.println '\"Grzegorz Brzeczyszczykiewicz\"' |""".stripMargin @@ -107,11 +106,11 @@ class TextTest extends InterpreterTest { "support converting values to display texts" in { val code = """ - |from Standard.Builtins import all |from Standard.Base.Data.List import Cons |from Standard.Base.Error.Common import all |from Standard.Base.Data.Text.Text import all |import Standard.Base.IO + |import Standard.Base.Nothing | |main = | IO.println (Cons Nothing Nothing).to_display_text From f0b45a71cb7339059e677cbccf26f8b4814e1364 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 10:10:40 +0200 Subject: [PATCH 33/73] Nits --- .../Base/0.0.0-dev/src/Data/{Text => }/Text.enso | 0 .../lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso | 2 +- distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 ++-- .../interpreter/node/expression/builtin/Nothing.java | 2 +- .../node/expression/builtin/error/CaughtPanic.java | 2 +- .../node/expression/builtin/error/Panic.java | 2 +- .../enso/interpreter/runtime/scope/ModuleScope.java | 1 - .../org/enso/interpreter/runtime/type/Constants.java | 4 ++-- .../test/instrument/RuntimeServerTest.scala | 10 +++++----- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 2 +- .../enso/interpreter/test/semantic/InteropTest.scala | 4 ++-- .../org/enso/interpreter/test/semantic/TextTest.scala | 2 +- 12 files changed, 17 insertions(+), 18 deletions(-) rename distribution/lib/Standard/Base/0.0.0-dev/src/Data/{Text => }/Text.enso (100%) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso similarity index 100% rename from distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text.enso rename to distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso index cbb9af002b4b..f15591d56b76 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso @@ -26,4 +26,4 @@ get_file path = @Builtin_Method "Prim_Io.get_file" Gets the textual path to the user's system-defined home directory. user_home : Text -user_home = @Builtin_Method "Prim_Io.user_home" \ No newline at end of file +user_home = @Builtin_Method "Prim_Io.user_home" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index c109f2efaec3..ae36d4593038 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -14,7 +14,7 @@ import project.Data.Ordering.Sort_Order import project.Data.Pair import project.Data.Range import project.Data.Ref -import project.Data.Text.Text +import project.Data.Text import project.Data.Text.Extensions import project.Data.Text.Matching import project.Data.Vector @@ -73,7 +73,7 @@ from project.Data.Range export Range https://www.pivotaltracker.com/story/show/181309938 from project.Data.Text.Extensions export Text, Split_Kind, Line_Ending_Style, Case, Location from project.Data.Text.Matching export Case_Insensitive, Text_Matcher, Regex_Matcher -from project.Data.Text.Text export all +from project.Data.Text export all from project.Error.Common export all from project.Error.Extensions export all from project.Function export all diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java index 54b9987be13d..16d99b042bb6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java @@ -3,4 +3,4 @@ import org.enso.interpreter.dsl.BuiltinType; @BuiltinType -public class Nothing extends Builtin {} \ No newline at end of file +public class Nothing extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 031c3a05b761..bae28014b5c8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -4,4 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params="payload,internal_original_exception") -public class CaughtPanic extends Builtin {} \ No newline at end of file +public class CaughtPanic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java index b810d421377c..caf28b6277dc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java @@ -4,4 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Panic extends Builtin {} \ No newline at end of file +public class Panic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 8a4fab360279..b05648d64c55 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -17,7 +17,6 @@ public class ModuleScope implements TruffleObject { private final Module module; private Map polyglotSymbols = new HashMap<>(); private Map constructors = new HashMap<>(); - private List builtins = new ArrayList<>(); private Map> methods = new HashMap<>(); private Map> conversions = new HashMap<>(); private Set imports = new HashSet<>(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index c863cfcc20ec..ccc0472b93e8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -5,7 +5,7 @@ public class Constants { public static final String ANY = "Standard.Base.Data.Any.Any"; public static final String ARRAY = "Standard.Base.Data.Array.Array"; - public static final String BOOLEAN = "Standard.Builtins.Main.Boolean"; + public static final String BOOLEAN = "Standard.Builtins.Data.Boolean.Boolean"; public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; public static final String ERROR = "Standard.Base.Error.Common.Error"; public static final String FUNCTION = "Standard.Base.Function.Function"; @@ -16,7 +16,7 @@ public class Constants { public static final String NUMBER = "Standard.Builtins.Main.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; - public static final String TEXT = "Standard.Base.Data.Text.Text"; + public static final String TEXT = "Standard.Base.Data.Text"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 0f72b5443001..337d79099fa4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -1384,16 +1384,16 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(118, 88) - val id1 = metadata.addItem(127, 15) - val id2 = metadata.addItem(147, 18) - val id3 = metadata.addItem(170, 15) + val idMain = metadata.addItem(113, 88) + val id1 = metadata.addItem(122, 15) + val id2 = metadata.addItem(142, 18) + val id3 = metadata.addItem(165, 15) // Note that Nothing.Nothing is on purpose. // If not provided the full name it will resolve the // expression type of Nothing to a Nothing module val code = """from Standard.Builtins import Number - |from Standard.Base.Data.Text.Text import all + |from Standard.Base.Data.Text import all |import Standard.Base.Nothing | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 90a07bae6d89..f36e49bc7682 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -727,7 +727,7 @@ class RuntimeSuggestionUpdatesTest val contents = """from Standard.Builtins import Number - |from Standard.Base.Data.Text.Text import all + |import Standard.Base.Data.Text |import Standard.Base.Nothing | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 90281bec9ad4..87b0650b9061 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -57,8 +57,8 @@ class InteropTest extends InterpreterTest { "work with unresolved symbols" in { val code = - """from Standard.Builtins import all - |from Standard.Base.Data.Text.Text import all + """from Standard.Builtins import Number + |from Standard.Base.Data.Text import all | |Number.add x = x + this |Text.add x = this + x diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index d824aa8df199..e7c65e0da385 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -108,7 +108,7 @@ class TextTest extends InterpreterTest { """ |from Standard.Base.Data.List import Cons |from Standard.Base.Error.Common import all - |from Standard.Base.Data.Text.Text import all + |import Standard.Base.Data.Text |import Standard.Base.IO |import Standard.Base.Nothing | From 8e7e15f743bd913ba72767e252527ace895f1e5f Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 11:52:01 +0200 Subject: [PATCH 34/73] Cons/Nil are no longer Builtin_Types Looked like an unnecessary relict from the past. This also revealed a small issues where `Cons` fields `head` and `tail` conflicted with `List`s methods of the same name. Previously we would ignore attempt to overload the methods because List was builtin. --- .../lib/Standard/Base/0.0.0-dev/src/Data/List.enso | 11 ++++------- .../interpreter/node/expression/builtin/Cons.java | 6 ------ .../enso/interpreter/node/expression/builtin/Nil.java | 6 ------ 3 files changed, 4 insertions(+), 19 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index b1ef02952e16..c1d6479220cd 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -17,17 +17,14 @@ import Standard.Base.Nothing type List ## The type that indicates the end of a cons list. - @Builtin_Type type Nil ## A cons cell for a cons list. Arguments: - - head: The element at this position in the list. - - tail: The rest of the list. - @Builtin_Type - type Cons head tail - + - x: The element at this position in the list. + - xs: The rest of the list. + type Cons x xs ## Computes the number of elements in the list. @@ -278,7 +275,7 @@ type List import Standard.Examples - example_head = Examples.list.head + example_head = Examples.list.x head : Any ! Empty_Error head = case this of Cons a _ -> a diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java deleted file mode 100644 index 744c3bda3cd2..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Cons.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.enso.interpreter.node.expression.builtin; - -import org.enso.interpreter.dsl.BuiltinType; - -@BuiltinType(params="head,tail") -public class Cons extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java deleted file mode 100644 index 0610cca42b4b..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nil.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.enso.interpreter.node.expression.builtin; - -import org.enso.interpreter.dsl.BuiltinType; - -@BuiltinType -public class Nil extends Builtin {} From b6ae3f0d9a1b859d4f49c338365426f2b1ae5bd6 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 12:50:41 +0200 Subject: [PATCH 35/73] Adapt benchmark fixtures List is no longer a builtin so AtomFixtures need to be adapted. Rather than constructing a list of million elements manually we just evaluate Enso code that does that. --- .../fixtures/semantic/AtomFixtures.scala | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 3704e0e91939..08e9941ddb57 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -7,20 +7,17 @@ import org.graalvm.polyglot.Value class AtomFixtures extends DefaultInterpreterRunner { val million: Long = 1000000 - def buildInputList(length: Long): Value = { - val builtins = - interpreterContext.executionContext.getTopScope - .getModule(Builtins.MODULE_NAME) - val nil = builtins.getConstructor("Nil") - val cons = builtins.getConstructor("Cons") - 1L.to(length).foldLeft(nil.newInstance()) { case (tail, el) => - cons.newInstance(el.asInstanceOf[Object], tail) - } - } - val millionElementList = buildInputList(million) + val millionElementList = eval( + s"""|from Standard.Base.Data.List import Cons,Nil + |from Standard.Base.Data.Number.Extensions import all + | + |main = + | res = (1.up_to $million).fold Nil (acc -> x -> Cons x acc) + | res + """.stripMargin) val generateListCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = length -> | generator = acc -> i -> if i == 0 then acc else @Tail_Call generator (Cons i acc) (i - 1) @@ -31,18 +28,18 @@ class AtomFixtures extends DefaultInterpreterRunner { val generateList = getMain(generateListCode) val generateListQualifiedCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = length -> - | generator = acc -> i -> if i == 0 then acc else @Tail_Call generator (Builtins.cons i acc) (i - 1) + | generator = acc -> i -> if i == 0 then acc else @Tail_Call generator (List.cons i acc) (i - 1) | - | res = generator Builtins.nil length + | res = generator List.nil length | res """.stripMargin val generateListQualified = getMain(generateListQualifiedCode) val reverseListCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = list -> | reverser = acc -> list -> case list of @@ -55,7 +52,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val reverseList = getMain(reverseListCode) val reverseListMethodsCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Cons.reverse = acc -> case this of | Cons h t -> @Tail_Call t.reverse (Cons h acc) @@ -69,7 +66,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val reverseListMethods = getMain(reverseListMethodsCode) val sumListCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = list -> | summator = acc -> list -> case list of @@ -82,7 +79,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumList = getMain(sumListCode) val sumListLeftFoldCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = list -> | fold = f -> acc -> list -> case list of @@ -95,7 +92,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumListLeftFold = getMain(sumListLeftFoldCode) val sumListFallbackCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = list -> | summator = acc -> list -> case list of @@ -108,7 +105,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumListFallback = getMain(sumListFallbackCode) val sumListMethodsCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Nil.sum = acc -> acc |Cons.sum = acc -> case this of @@ -121,7 +118,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumListMethods = getMain(sumListMethodsCode) val mapReverseListCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Nil.mapReverse = f -> acc -> acc |Cons.mapReverse = f -> acc -> case this of @@ -134,7 +131,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val mapReverseList = getMain(mapReverseListCode) val mapReverseListCurryCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |Nil.mapReverse = f -> acc -> acc |Cons.mapReverse = f -> acc -> case this of From 870ef1af80761df65aac30b9f1051a1472616d75 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 12:59:41 +0200 Subject: [PATCH 36/73] Remove unused imports --- .../enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala | 2 -- 1 file changed, 2 deletions(-) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 08e9941ddb57..f23ae5fd3101 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -1,8 +1,6 @@ package org.enso.interpreter.bench.fixtures.semantic import org.enso.interpreter.test.DefaultInterpreterRunner -import org.enso.interpreter.runtime.builtin.Builtins -import org.graalvm.polyglot.Value class AtomFixtures extends DefaultInterpreterRunner { val million: Long = 1000000 From 70d558d65ba3f14ab095e57115f703a27cac1174 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 16:47:56 +0200 Subject: [PATCH 37/73] Rename local 'reverse' method in List benchmarks `reverse` is defined in `List` module and since `List` type was moved to stdlib, method resolution gives a higher priority to the one defined in stdlib. Local methods are only looked up when the former fails, which is clearly not the case now. We should probably have some warnings for that. --- .../interpreter/bench/fixtures/semantic/AtomFixtures.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index f23ae5fd3101..d97d3ddfa276 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -52,13 +52,13 @@ class AtomFixtures extends DefaultInterpreterRunner { val reverseListMethodsCode = """from Standard.Base.Data.List import all | - |Cons.reverse = acc -> case this of + |Cons.rev = acc -> case this of | Cons h t -> @Tail_Call t.reverse (Cons h acc) | - |Nil.reverse = acc -> acc + |Nil.rev = acc -> acc | |main = list -> - | res = list.reverse Nil + | res = list.rev Nil | res |""".stripMargin val reverseListMethods = getMain(reverseListMethodsCode) From 4f1fe32aad8c6bbb66e1ba4a7dca1eb1cd20074a Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 16:53:32 +0200 Subject: [PATCH 38/73] Amend benchmark with missing import Nothing is now in stdlib. --- .../interpreter/bench/fixtures/semantic/RecursionFixtures.scala | 1 + 1 file changed, 1 insertion(+) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala index 1ccd1a50c116..d976cb5d8f44 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala @@ -76,6 +76,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val nestedThunkSumCode = """from Standard.Builtins import all + |import Standard.Base.Nothing | |doNTimes = n -> ~block -> | block From 6cfeca08c8bc8099dcb60d9dd6d93f371660fc21 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 18:00:09 +0200 Subject: [PATCH 39/73] Make benchmarks happy again Make use of CompilationFinal annotation to allow for constant folding of most of referencing most of builtin types. Also Prim_Text_Helper doesn't really have to be a builtin type. --- .../Base/0.0.0-dev/src/Data/Text.enso | 15 -- .../src/Data/Text/Prim_Text_Helper.enso | 7 + .../node/controlflow/caseexpr/CaseNode.java | 3 +- .../builtin/state/GetStateNode.java | 6 +- .../builtin/state/PutStateNode.java | 4 +- .../expression/constant/EnsoProjectNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 153 ++++++++++---- .../interpreter/runtime/builtin/Error.java | 196 ++++++++++++++---- .../enso/compiler/codegen/IrToTruffle.scala | 39 ++-- test/Benchmarks/src/Text/Build.enso | 3 +- 10 files changed, 303 insertions(+), 125 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso index 59ece2441502..16aa5d40c794 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -23,18 +23,3 @@ type Text "Hello" + ", world!" + : Text -> Text + that = @Builtin_Method "Text.+" - -## Internal text utilities for inspecting text primitives. -type Prim_Text_Helper - - ## PRIVATE - - A container for primitive text operations. - @Builtin_Type - type Prim_Text_Helper - - ## PRIVATE - - Forces flattening of a text value. - optimize : Text - optimize = @Builtin_Method "Prim_Text_Helpers.optimize" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso new file mode 100644 index 000000000000..d223dd5d0eb4 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso @@ -0,0 +1,7 @@ +## Internal text utilities for inspecting text primitives. + +## PRIVATE + + Forces flattening of a text value. +optimize : Text +optimize = @Builtin_Method "Prim_Text_Helpers.optimize" \ No newline at end of file diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java index 2b79e93f5db1..227b05b5bacc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java @@ -96,8 +96,7 @@ public Object doMatch(VirtualFrame frame, Object object) { Context.get(this) .getBuiltins() .error() - .inexhaustivePatternMatchError() - .newInstance(object), + .makeInexhaustivePatternMatchError(object), this); } catch (BranchSelectedException e) { // Note [Branch Selection Control Flow] diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java index f2d43c5bb64e..b296d997d081 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java @@ -51,7 +51,7 @@ Object doMultiUncached( int idx = state.indexOf(key); if (idx == SmallMap.NOT_FOUND) { return DataflowError.withoutTrace( - Context.get(this).getBuiltins().error().uninitializedState().newInstance(key), this); + Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this); } else { return state.getValues()[idx]; } @@ -61,13 +61,13 @@ Object doMultiUncached( Object doEmpty( EmptyMap state, Object _this, Object key) { return DataflowError.withoutTrace( - Context.get(this).getBuiltins().error().uninitializedState().newInstance(key), this); + Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this); } @Specialization Object doSingletonError( SingletonMap state, Object _this, Object key) { return DataflowError.withoutTrace( - Context.get(this).getBuiltins().error().uninitializedState().newInstance(key), this); + Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java index 0c9ff2499196..d1b5f6713635 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java @@ -59,7 +59,7 @@ Stateful doMultiUncached( return new Stateful( state, DataflowError.withoutTrace( - Context.get(this).getBuiltins().error().uninitializedState().newInstance(key), this)); + Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this)); } else { return doExistingMultiCached(state, _this, key, new_state, key, state.getKeys(), index); } @@ -74,6 +74,6 @@ Stateful doError( return new Stateful( state, DataflowError.withoutTrace( - Context.get(this).getBuiltins().error().uninitializedState().newInstance(key), this)); + Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this)); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java index ba02ea1ac7f1..7f2adda80497 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java @@ -29,7 +29,7 @@ public EnsoProjectNode( } else { result = DataflowError.withoutTrace( - context.getBuiltins().error().moduleNotInPackageError().newInstance(), this); + context.getBuiltins().error().makeModuleNotInPackageError(), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index a4bf298a1825..539bd0effc11 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -24,9 +24,6 @@ import org.enso.interpreter.node.expression.builtin.bool.True; import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; -import org.enso.interpreter.node.expression.builtin.error.CaughtPanic; -import org.enso.interpreter.node.expression.builtin.error.Panic; -import org.enso.interpreter.node.expression.builtin.function.ExplicitCallFunctionMethodGen; import org.enso.interpreter.node.expression.builtin.mutable.Array; import org.enso.interpreter.node.expression.builtin.mutable.Ref; import org.enso.interpreter.node.expression.builtin.runtime.GCMethodGen; @@ -63,10 +60,8 @@ public static class Debug { } } - private HashMap>> builtinNodes; - // TODO Consider dropping the map and just assigning to a single variable since builtin types - // should be unique - private HashMap builtinTypes; + private final Map>> builtinMethodNodes; + private final Map builtins; private final AtomConstructor debug; private final AtomConstructor projectDescription; @@ -80,6 +75,40 @@ public static class Debug { private final System system; private final Special special; + // Builtin types + @CompilerDirectives.CompilationFinal + private AtomConstructor any; + + @CompilerDirectives.CompilationFinal + private AtomConstructor nothing; + + @CompilerDirectives.CompilationFinal + private AtomConstructor function; + + @CompilerDirectives.CompilationFinal + private AtomConstructor polyglot; + + @CompilerDirectives.CompilationFinal + private AtomConstructor text; + + @CompilerDirectives.CompilationFinal + private AtomConstructor array; + + @CompilerDirectives.CompilationFinal + private AtomConstructor bool; + + @CompilerDirectives.CompilationFinal + private AtomConstructor trueConstructor; + + @CompilerDirectives.CompilationFinal + private AtomConstructor falseConstructor; + + @CompilerDirectives.CompilationFinal + private AtomConstructor dataflowError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor ref; + /** * Creates an instance with builtin methods installed. * @@ -89,9 +118,15 @@ public Builtins(Context context) { Language language = context.getLanguage(); module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); scope = module.compileScope(context); - builtinNodes = new HashMap<>(); - builtinTypes = new HashMap<>(); + builtins = new HashMap<>(); + List builtinTypes = readBuiltinTypesMetadata(scope); + builtinMethodNodes = readBuiltinMethodsMetadata(scope); + registerBuiltinMethods(builtinTypes, scope, language); + + error = new Error(this); + + // TODO: Builtins that are not yet moved to stdlib debug = new AtomConstructor("Debug", scope).initializeFields(); Warning.initWarningMethods(language, scope); projectDescription = @@ -100,7 +135,7 @@ public Builtins(Context context) { new ArgumentDefinition( 0, "prim_root_file", ArgumentDefinition.ExecutionMode.EXECUTE), new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); - error = new Error(this); + number = new Number(language, scope); ordering = new Ordering(language, scope); resource = new Resource(language, scope); @@ -140,15 +175,13 @@ public Builtins(Context context) { thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); - readBuiltinsMetadata(scope); - assignMethodsToBuiltins(readBuiltinTypesMetadata(scope), scope, language); } - public void assignMethodsToBuiltins(List builtins, ModuleScope scope, Language language) { + public void registerBuiltinMethods(List builtins, ModuleScope scope, Language language) { for (AtomConstructor atom: builtins) { String tpeName = atom.getName(); - builtinTypes.put(tpeName, atom); - Map> methods = builtinNodes.get(tpeName); + this.builtins.put(tpeName, atom); + Map> methods = builtinMethodNodes.get(tpeName); if (methods != null) { methods.forEach((methodName, clazz) -> { Optional fun; @@ -164,6 +197,7 @@ public void assignMethodsToBuiltins(List builtins, ModuleScope } } } + /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ public boolean isIrInitialized() { return this.module.getIr() != null; @@ -220,6 +254,7 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { AtomConstructor builtin; builtin = new AtomConstructor(builtinMeta[0], scope, true); + if (builtinMeta.length == 2) { builtin = builtin.initializeFields(); } else { @@ -234,8 +269,8 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { return builtin; }).filter(b -> b != null).collect(Collectors.toList()); } - - private void readBuiltinsMetadata(ModuleScope scope) { + + private Map>> readBuiltinMethodsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(MethodDefinition.META_PATH)) { @@ -244,6 +279,7 @@ private void readBuiltinsMetadata(ModuleScope scope) { lines = new ArrayList<>(); ioe.printStackTrace(); } + Map>> methodNodes = new HashMap<>(); lines.forEach(line -> { String[] builtinMeta = line.split(":"); @@ -259,19 +295,19 @@ private void readBuiltinsMetadata(ModuleScope scope) { String builtinMethodOwner = builtinName[0]; String builtinMethodName = builtinName[1]; scope.getLocalConstructor(builtinMethodOwner).ifPresentOrElse(constr -> { - Map> atomNodes = builtinNodes.get(builtinMethodOwner); + Map> atomNodes = methodNodes.get(builtinMethodOwner); if (atomNodes == null) { atomNodes = new HashMap<>(); // TODO: move away from String Map once Builtins are gone - builtinNodes.put(constr.getName(), atomNodes); + methodNodes.put(constr.getName(), atomNodes); } atomNodes.put(builtinMethodName, clazz); }, () -> { - Map> atomNodes = builtinNodes.get(builtinMethodOwner); + Map> atomNodes = methodNodes.get(builtinMethodOwner); if (atomNodes == null) { atomNodes = new HashMap<>(); // TODO: move away from String Map once Builtins are gone - builtinNodes.put(builtinMethodOwner, atomNodes); + methodNodes.put(builtinMethodOwner, atomNodes); } atomNodes.put(builtinMethodName, clazz); }); @@ -279,11 +315,12 @@ private void readBuiltinsMetadata(ModuleScope scope) { e.printStackTrace(); } }); + return methodNodes; } public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone - Map> atomNodes = builtinNodes.get(atom.getName()); + Map> atomNodes = builtinMethodNodes.get(atom.getName()); if (atomNodes == null) return Optional.empty(); Class clazz = atomNodes.get(methodName); @@ -304,7 +341,7 @@ public AtomConstructor getBuiltinType(Class clazz) { } public AtomConstructor getBuiltinType(String name) { - return builtinTypes.get(name); + return builtins.get(name); } /** @@ -313,7 +350,11 @@ public AtomConstructor getBuiltinType(String name) { * @return the {@code Nothing} atom constructor */ public AtomConstructor nothing() { - return getBuiltinType(Nothing.class); + if (nothing == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + nothing = getBuiltinType(Nothing.class); + } + return nothing; } /** @@ -322,7 +363,11 @@ public AtomConstructor nothing() { * @return the {@code Text} part of builtins. */ public AtomConstructor text() { - return getBuiltinType(Text.class); + if (text == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + text = getBuiltinType(Text.class); + } + return text; } /** @@ -331,7 +376,11 @@ public AtomConstructor text() { * @return the {@code Function} atom constructor */ public AtomConstructor function() { - return getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); + if (function == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + function = getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); + } + return function; } /** @@ -345,17 +394,29 @@ public Number number() { /** @return the Boolean constructor. */ public AtomConstructor bool() { - return this.getBuiltinType(Boolean.class); + if (bool == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + bool = getBuiltinType(Boolean.class); + } + return bool; } /** @return the True constructor. */ public AtomConstructor trueAtom() { - return this.getBuiltinType(True.class); + if (trueConstructor == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + trueConstructor = getBuiltinType(True.class); + } + return trueConstructor; } /** @return the False constructor. */ public AtomConstructor falseAtom() { - return this.getBuiltinType(False.class); + if (falseConstructor == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + falseConstructor = getBuiltinType(False.class); + } + return falseConstructor; } @@ -370,7 +431,11 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - return this.getBuiltinType(Any.class); + if (any == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + any = getBuiltinType(Any.class); + } + return any; } /** @@ -394,27 +459,39 @@ public System system() { /** @return the Array constructor. */ public AtomConstructor array() { - return this.getBuiltinType(Array.class); + if (array == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + array = getBuiltinType(Array.class); + } + return array; } /** @return the Ref constructor. */ public AtomConstructor ref() { - return this.getBuiltinType(Ref.class); + if (ref == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + ref = getBuiltinType(Ref.class); + } + return ref; } /** @return the container for polyglot-related builtins. */ public AtomConstructor polyglot() { - return this.getBuiltinType(Polyglot.class); + if (polyglot == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + polyglot = getBuiltinType(Polyglot.class); + } + return polyglot; } /** @return the {@code Caught_Panic} atom constructor */ public AtomConstructor caughtPanic() { - return this.getBuiltinType(CaughtPanic.class); + return this.error.caughtPanic(); } /** @return the {@code Panic} atom constructor */ public AtomConstructor panic() { - return this.getBuiltinType(Panic.class); + return this.error.panic(); } /** @return the container for ordering-related builtins */ @@ -424,7 +501,11 @@ public Ordering ordering() { /** @return the container for the dataflow error-related builtins */ public AtomConstructor dataflowError() { - return this.getBuiltinType(org.enso.interpreter.node.expression.builtin.Error.class); + if (dataflowError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + dataflowError = getBuiltinType(org.enso.interpreter.node.expression.builtin.Error.class); + } + return dataflowError; } public Special special() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index 4826c9c42baf..b372fb5a5847 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java @@ -13,55 +13,129 @@ /** Container for builtin Error types */ public class Error { - private Builtins builtins; + @CompilerDirectives.CompilationFinal + private AtomConstructor syntaxError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor typeError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor compileError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor inexhaustivePatternMatchError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor uninitializedState; + + @CompilerDirectives.CompilationFinal + private AtomConstructor noSuchMethodError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor noSuchConversionError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor polyglotError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor moduleNotInPackageError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor arithmeticError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor invalidArrayIndexError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor arityError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor unsupportedArgumentsError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor moduleDoesNotExistError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor notInvokableError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor invalidConversionTargetError; + + @CompilerDirectives.CompilationFinal + private AtomConstructor panic; + + @CompilerDirectives.CompilationFinal + private AtomConstructor caughtPanic; + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorDivideByZero; private static final Text shiftTooBigMessage = Text.create("Shift amount too large."); private static final Text divideByZeroMessage = Text.create("Cannot divide by zero."); - /** - * Creates and registers the relevant constructors. - * - * @param language the current language instance. - * @param scope the scope to register constructors in. - */ + private final Builtins builtins; + public Error(Builtins builtins) { this.builtins = builtins; - arithmeticErrorShiftTooBig = null; - arithmeticErrorDivideByZero = null; } - /** @return the builtin {@code Syntax_Error} atom constructor. */ - public AtomConstructor syntaxError() { - return builtins.getBuiltinType(SyntaxError.class); + public Atom makeSyntaxError(Object message) { + if (syntaxError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + syntaxError = builtins.getBuiltinType(SyntaxError.class); + } + return syntaxError.newInstance(message); } - /** @return the builtin {@code Type_Error} atom constructor. */ - public AtomConstructor typeError() { - return builtins.getBuiltinType(TypeError.class); + public Atom makeCompileError(Object message) { + if (compileError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + compileError = builtins.getBuiltinType(CompileError.class); + } + return compileError.newInstance(message); + } + + public Atom makeInexhaustivePatternMatchError(Object message) { + if (inexhaustivePatternMatchError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + inexhaustivePatternMatchError = builtins.getBuiltinType(InexhaustivePatternMatchError.class); + } + return inexhaustivePatternMatchError.newInstance(message); } - /** @return the builtin {@code Compile_Error} atom constructor. */ - public AtomConstructor compileError() { - return builtins.getBuiltinType(CompileError.class); + public Atom makeUninitializedStateError(Object key) { + if (uninitializedState == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + uninitializedState = builtins.getBuiltinType(UninitializedState.class); + } + return uninitializedState.newInstance(key); } - /** @return the builtin {@code Inexhaustive_Pattern_Match_Error} atom constructor. */ - public AtomConstructor inexhaustivePatternMatchError() { - return builtins.getBuiltinType(InexhaustivePatternMatchError.class); + public Atom makeModuleNotInPackageError() { + if (moduleNotInPackageError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + moduleNotInPackageError = builtins.getBuiltinType(ModuleNotInPackageError.class); + } + return moduleNotInPackageError.newInstance(); } - /** @return the builtin {@code Uninitialized_State} atom constructor. */ - public AtomConstructor uninitializedState() { - return builtins.getBuiltinType(UninitializedState.class); + public AtomConstructor panic() { + if (panic == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + panic = builtins.getBuiltinType(Panic.class); + } + return panic; } - /** @return the builtin {@code Module_Not_In_Package_Error} atom constructor. */ - public AtomConstructor moduleNotInPackageError() { - return builtins.getBuiltinType(ModuleNotInPackageError.class); + public AtomConstructor caughtPanic() { + if (caughtPanic == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + caughtPanic = builtins.getBuiltinType(CaughtPanic.class); + } + return caughtPanic; } /** @@ -72,16 +146,28 @@ public AtomConstructor moduleNotInPackageError() { * @return a runtime representation of the error */ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { - return builtins.getBuiltinType(NoSuchMethodError.class).newInstance(target, symbol); + if (noSuchMethodError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + noSuchMethodError = builtins.getBuiltinType(NoSuchMethodError.class); + } + return noSuchMethodError.newInstance(target, symbol); } public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { - return builtins.getBuiltinType(NoSuchConversionError.class).newInstance(target, that, conversion); + if (noSuchConversionError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + noSuchConversionError = builtins.getBuiltinType(NoSuchConversionError.class); + } + return noSuchConversionError.newInstance(target, that, conversion); } public Atom makeInvalidConversionTargetError(Object target) { - return builtins.getBuiltinType(InvalidConversionTargetError.class).newInstance(target); + if (invalidConversionTargetError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + invalidConversionTargetError = builtins.getBuiltinType(InvalidConversionTargetError.class); + } + return invalidConversionTargetError.newInstance(target); } /** @@ -93,7 +179,11 @@ public Atom makeInvalidConversionTargetError(Object target) { * @return a runtime representation of the error. */ public Atom makeTypeError(Object expected, Object actual, String name) { - return builtins.getBuiltinType(TypeError.class).newInstance(expected, actual, Text.create(name)); + if (typeError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + typeError = builtins.getBuiltinType(TypeError.class); + } + return typeError.newInstance(expected, actual, Text.create(name)); } /** @@ -103,7 +193,11 @@ public Atom makeTypeError(Object expected, Object actual, String name) { * @return a runtime representation of the polyglot error. */ public Atom makePolyglotError(Object cause) { - return builtins.getBuiltinType(PolyglotError.class).newInstance(cause); + if (polyglotError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + polyglotError = builtins.getBuiltinType(PolyglotError.class); + } + return polyglotError.newInstance(cause); } /** @@ -113,12 +207,17 @@ public Atom makePolyglotError(Object cause) { * @return a runtime representation of the arithmetic error */ public Atom makeArithmeticError(Text reason) { - return builtins.getBuiltinType(ArithmeticError.class).newInstance(reason); + if (arithmeticError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + arithmeticError = builtins.getBuiltinType(ArithmeticError.class); + } + return arithmeticError.newInstance(reason); } /** @return An arithmetic error representing a too-large shift for the bit shift. */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); arithmeticErrorShiftTooBig = makeArithmeticError(shiftTooBigMessage); } return arithmeticErrorShiftTooBig; @@ -127,6 +226,7 @@ public Atom getShiftAmountTooLargeError() { /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); arithmeticErrorDivideByZero = makeArithmeticError(divideByZeroMessage); } return arithmeticErrorDivideByZero; @@ -138,7 +238,11 @@ public Atom getDivideByZeroError() { * @return An error representing that the {@code index} is not valid in {@code array} */ public Atom makeInvalidArrayIndexError(Object array, Object index) { - return builtins.getBuiltinType(InvalidArrayIndexError.class).newInstance(array, index); + if (invalidArrayIndexError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + invalidArrayIndexError = builtins.getBuiltinType(InvalidArrayIndexError.class); + } + return invalidArrayIndexError.newInstance(array, index); } /** @@ -148,7 +252,11 @@ public Atom makeInvalidArrayIndexError(Object array, Object index) { * @return an error informing about the arity being mismatched */ public Atom makeArityError(long expected_min, long expected_max, long actual) { - return builtins.getBuiltinType(ArityError.class).newInstance(expected_min, expected_max, actual); + if (arityError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + arityError = builtins.getBuiltinType(ArityError.class); + } + return arityError.newInstance(expected_min, expected_max, actual); } /** @@ -157,7 +265,11 @@ public Atom makeArityError(long expected_min, long expected_max, long actual) { * given method callp */ public Atom makeUnsupportedArgumentsError(Object[] args) { - return builtins.getBuiltinType(UnsupportedArgumentTypes.class).newInstance(new Array(args)); + if (unsupportedArgumentsError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + unsupportedArgumentsError = builtins.getBuiltinType(UnsupportedArgumentTypes.class); + } + return unsupportedArgumentsError.newInstance(new Array(args)); } /** @@ -165,7 +277,11 @@ public Atom makeUnsupportedArgumentsError(Object[] args) { * @return a module does not exist error */ public Atom makeModuleDoesNotExistError(String name) { - return builtins.getBuiltinType(ModuleDoesNotExist.class).newInstance(Text.create(name)); + if (moduleDoesNotExistError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + moduleDoesNotExistError = builtins.getBuiltinType(ModuleDoesNotExist.class); + } + return moduleDoesNotExistError.newInstance(Text.create(name)); } /** @@ -173,6 +289,10 @@ public Atom makeModuleDoesNotExistError(String name) { * @return a not invokable error */ public Atom makeNotInvokableError(Object target) { - return builtins.getBuiltinType(NotInvokableError.class).newInstance(target); + if (notInvokableError == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + notInvokableError = builtins.getBuiltinType(NotInvokableError.class); + } + return notInvokableError.newInstance(target); } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 7a64279c7fd3..fbeb5d462bb6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -649,8 +649,7 @@ class IrToTruffle( ErrorNode.build( context.getBuiltins .error() - .syntaxError() - .newInstance( + .makeSyntaxError( Text.create( "Type operators are not currently supported at runtime." ) @@ -695,8 +694,7 @@ class IrToTruffle( val error = context.getBuiltins .error() - .compileError() - .newInstance(Text.create(message)) + .makeCompileError(Text.create(message)) setLocation(ErrorNode.build(error), caseExpr.location) } @@ -1093,53 +1091,43 @@ class IrToTruffle( case err: Error.Syntax => context.getBuiltins .error() - .syntaxError() - .newInstance(Text.create(err.message)) + .makeSyntaxError(Text.create(err.message)) case err: Error.Redefined.Binding => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Redefined.Method => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Redefined.MethodClashWithAtom => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Redefined.Conversion => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Redefined.Atom => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Redefined.ThisArg => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Unexpected.TypeSignature => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Resolution => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case err: Error.Conversion => context.getBuiltins .error() - .compileError() - .newInstance(Text.create(err.message)) + .makeCompileError(Text.create(err.message)) case _: Error.Pattern => throw new CompilerError( "Impossible here, should be handled in the pattern match." @@ -1330,8 +1318,7 @@ class IrToTruffle( ErrorNode.build( context.getBuiltins .error() - .syntaxError() - .newInstance( + .makeSyntaxError( Text.create( "Typeset literals are not yet supported at runtime." ) diff --git a/test/Benchmarks/src/Text/Build.enso b/test/Benchmarks/src/Text/Build.enso index 93dcf90d8905..2c93330d9307 100644 --- a/test/Benchmarks/src/Text/Build.enso +++ b/test/Benchmarks/src/Text/Build.enso @@ -1,9 +1,8 @@ from Standard.Base import all +import Standard.Base.Data.Text.Prim_Text_Helper import Standard.Test.Bench -from Standard.Builtins import Prim_Text_Helper - polyglot java import java.lang.StringBuilder build_long n = From b6fe9ccd83055de6fd9326c61bdca480f273c197 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 21 Apr 2022 21:47:13 +0200 Subject: [PATCH 40/73] fix typo --- .../enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index d97d3ddfa276..a7fdb21a4bce 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -53,7 +53,7 @@ class AtomFixtures extends DefaultInterpreterRunner { """from Standard.Base.Data.List import all | |Cons.rev = acc -> case this of - | Cons h t -> @Tail_Call t.reverse (Cons h acc) + | Cons h t -> @Tail_Call t.rev (Cons h acc) | |Nil.rev = acc -> acc | From f17d3cb267affeca502d6415bad55594405efeb9 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 22 Apr 2022 14:29:31 +0200 Subject: [PATCH 41/73] Move runtime builtin types to stdlib Towards removing all those `from Standard.Builtins import all`. Added some documentation for Builtins methods. Moved `Text.==` from the extension module to the Text type so that it gets picked up rather than `Any.==`. --- .../Base/0.0.0-dev/src/Data/List.enso | 3 +- .../Base/0.0.0-dev/src/Data/Ordering.enso | 27 +- .../Base/0.0.0-dev/src/Data/Text.enso | 24 ++ .../0.0.0-dev/src/Data/Text/Extensions.enso | 22 - .../src/Data/Text/Prim_Text_Helper.enso | 2 +- .../0.0.0-dev/src/Data/Time/Duration.enso | 1 + .../Base/0.0.0-dev/src/Data/Vector.enso | 2 +- .../Base/0.0.0-dev/src/Error/Common.enso | 10 +- .../Standard/Base/0.0.0-dev/src/Function.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 8 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 2 - .../Base/0.0.0-dev/src/Meta/Enso_Project.enso | 62 +-- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Runtime.enso | 98 +++++ .../Base/0.0.0-dev/src/Runtime/Debug.enso | 36 ++ .../0.0.0-dev/src/Runtime/Extensions.enso | 30 -- .../Base/0.0.0-dev/src/Runtime/Resource.enso | 77 ++++ .../Base/0.0.0-dev/src/Runtime/State.enso | 52 +++ .../Base/0.0.0-dev/src/Runtime/Thread.enso | 19 + .../Base/0.0.0-dev/src/Runtime/Unsafe.enso | 14 + .../Standard/Base/0.0.0-dev/src/System.enso | 60 +++ .../Base/0.0.0-dev/src/System/File.enso | 1 + .../Base/0.0.0-dev/src/System/Platform.enso | 4 +- .../Base/0.0.0-dev/src/System/Process.enso | 3 +- .../Standard/Base/0.0.0-dev/src/Warning.enso | 1 + .../0.0.0-dev/src/Connection/Connection.enso | 2 + .../src/Internal/Unique_Name_Strategy.enso | 1 + .../Standard/Test/0.0.0-dev/src/Bench.enso | 1 + .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 2 + .../enso/launcher/upgrade/UpgradeSpec.scala | 2 +- .../fixtures/semantic/CallableFixtures.scala | 2 +- .../fixtures/semantic/RecursionFixtures.scala | 8 +- .../builtin/meta/ProjectDescription.java | 7 + .../expression/builtin/ordering/Equal.java | 9 + .../expression/builtin/ordering/Greater.java | 8 + .../expression/builtin/ordering/Less.java | 8 + .../expression/builtin/ordering/Ordering.java | 8 + .../builtin/resource/ManagedResource.java | 8 + .../builtin/system/CreateProcessNode.java | 4 +- .../builtin/system/SystemProcessResult.java | 8 + .../org/enso/interpreter/runtime/Module.java | 13 +- .../interpreter/runtime/builtin/Builtins.java | 132 +++--- .../interpreter/runtime/builtin/Debug.java | 8 + .../interpreter/runtime/builtin/Ordering.java | 60 ++- .../interpreter/runtime/builtin/Resource.java | 34 -- .../interpreter/runtime/builtin/System.java | 42 +- .../callable/atom/AtomConstructor.java | 8 + .../runtime/src/main/resources/Builtins.enso | 390 ------------------ .../test/instrument/ReplTest.scala | 28 +- .../instrument/RuntimeInstrumentTest.scala | 96 ++--- .../test/instrument/RuntimeServerTest.scala | 10 +- .../semantic/CompileDiagnosticsTest.scala | 2 - .../interpreter/test/semantic/EvalTest.scala | 12 +- .../test/semantic/RuntimeManagementTest.scala | 8 +- .../interpreter/test/semantic/StateTest.scala | 20 +- .../test/semantic/SystemProcessTest.scala | 48 +-- test/Benchmarks/src/Main.enso | 2 + test/Tests/src/Data/List_Spec.enso | 1 + test/Tests/src/Resource/Bracket_Spec.enso | 1 + test/Tests/src/Semantic/Runtime_Spec.enso | 3 +- test/Tests/src/System/Process_Spec.enso | 2 + 61 files changed, 793 insertions(+), 767 deletions(-) create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/State.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Thread.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Unsafe.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/System.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Resource.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index c1d6479220cd..09d23567e92e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,7 +1,8 @@ -from Standard.Builtins import all +from Standard.Builtins import Number,Integer from Standard.Base.Error.Common import Error from Standard.Base.Data.Boolean import True, False import Standard.Base.Nothing +import Standard.Base.Runtime.Unsafe ## The basic cons-list type. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso index 8810b4dfd88f..f2622d904168 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso @@ -1,9 +1,3 @@ -from Standard.Base import all - -from Standard.Builtins import Less, Equal, Greater - -from Standard.Builtins export Less, Equal, Greater - ## Converts a sign-based representation of ordering to Enso's native ordering. Arguments: @@ -25,9 +19,24 @@ from_sign sign = if sign == 0 then Equal else The result should be returned in terms of how `this` orders in comparison to `that`. So, if `this` is greater than `that`, you should return `Greater.` type Ordering - Less - Equal - Greater + + ## A representation of the relative ordering between two values. + + These values must be able to be ordered with respect to each other. + @Builtin_Type + type Ordering + + ## A representation that the first value orders as less than the second. + @Builtin_Type + type Less + + ## A representation that the first value orders as equal to the second. + @Builtin_Type + type Equal + + ## A representation that the first value orders as greater than the second. + @Builtin_Type + type Greater ## Converts the ordering to the signed notion of ordering based on integers. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso index 16aa5d40c794..022a39f9412c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -1,3 +1,6 @@ +import Standard.Base.Meta +polyglot java import org.enso.base.Text_Utils + ## Enso's text type. type Text @@ -23,3 +26,24 @@ type Text "Hello" + ", world!" + : Text -> Text + that = @Builtin_Method "Text.+" + + ## Checks whether `this` is equal to `that`. + + Arguments: + - that: The text to compare `this` for equality with. + + ! Unicode Equality + The definition of equality includes Unicode canonicalization. I.e. two + texts are equal if they are identical after canonical decomposition. This + ensures that different ways of expressing the same character in the + underlying binary representation are considered equal. + + > Example + The string 'é' (i.e. the character U+00E9, LATIN SMALL LETTER E WITH ACUTE) + is canonically the same as the string 'e\u0301' (i.e. the letter `e` + followed by U+0301, COMBINING ACUTE ACCENT). Therefore: + + ('é' == 'e\u0301') == True + == : Any -> Boolean + == that = if Meta.is_same_object this Text then Meta.is_same_object that Text else + Text_Utils.equals this that \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso index 0dd6d8c7bc8b..a6f8b27a80e3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso @@ -1,7 +1,6 @@ ## Methods for operating on `Text` in Enso. from Standard.Base import all -from Standard.Builtins import Text, Prim_Text_Helpers import Standard.Base.Data.Text.Regex import Standard.Base.Data.Text.Regex.Mode @@ -527,27 +526,6 @@ Text.words keep_whitespace=False = bldr.to_vector -## Checks whether `this` is equal to `that`. - - Arguments: - - that: The text to compare `this` for equality with. - - ! Unicode Equality - The definition of equality includes Unicode canonicalization. I.e. two - texts are equal if they are identical after canonical decomposition. This - ensures that different ways of expressing the same character in the - underlying binary representation are considered equal. - - > Example - The string 'é' (i.e. the character U+00E9, LATIN SMALL LETTER E WITH ACUTE) - is canonically the same as the string 'e\u0301' (i.e. the letter `e` - followed by U+0301, COMBINING ACUTE ACCENT). Therefore: - - ('é' == 'e\u0301') == True -Text.== : Any -> Boolean -Text.== that = if Meta.is_same_object this Text then Meta.is_same_object that Text else - Text_Utils.equals this that - ## Checks whether `this` is equal to `that`, ignoring the case of the texts. Arguments: diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso index d223dd5d0eb4..c8ad1ea9cbf4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso @@ -4,4 +4,4 @@ Forces flattening of a text value. optimize : Text -optimize = @Builtin_Method "Prim_Text_Helpers.optimize" \ No newline at end of file +optimize = @Builtin_Method "Prim_Text_Helpers.optimize" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Duration.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Duration.enso index 1f92bf805ec2..e6d3e55d9b5f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Duration.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Duration.enso @@ -1,6 +1,7 @@ from Standard.Base import all import Standard.Base.Data.Time +import Standard.Base.System polyglot java import java.time.Duration as Java_Duration polyglot java import java.time.Period as Java_Period diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso index d916185fa430..318cc3529ce5 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso @@ -1,5 +1,5 @@ from Standard.Base import all -from Standard.Builtins import Unsupported_Argument_Types +import Standard.Base.Runtime.Unsafe ## Creates a new vector of the given length, initializing elements using the provided constructor function. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 1a080955b39c..cfe6f62fd5ee 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -1,6 +1,6 @@ from Standard.Base import all import Standard.Base.Data.Json -from Standard.Base.Runtime.Extensions as Runtime_Extensions import Stack_Trace_Element +import Standard.Base.Runtime ## Dataflow errors. type Error @@ -136,7 +136,7 @@ type Error The ordering of the resulting vector is such that the top stack frame is the first element. - stack_trace : Vector.Vector Stack_Trace_Element + stack_trace : Vector.Vector Runtime.Stack_Trace_Element stack_trace = Panic.get_attached_stack_trace this @@ -202,7 +202,7 @@ type Caught_Panic convert_to_dataflow_error = @Builtin_Method "Caught_Panic.convert_to_dataflow_error" ## Returns the stack trace of the caught panic. - stack_trace : Vector.Vector Stack_Trace_Element + stack_trace : Vector.Vector Runtime.Stack_Trace_Element stack_trace = Panic.get_attached_stack_trace this @@ -275,14 +275,14 @@ type Panic The ordering of the resulting vector is such that the top stack frame is the first element. - get_attached_stack_trace : Caught_Panic | Throwable -> Vector.Vector Stack_Trace_Element + get_attached_stack_trace : Caught_Panic | Throwable -> Vector.Vector Runtime.Stack_Trace_Element get_attached_stack_trace error = throwable = case error of Caught_Panic _ internal_original_exception -> internal_original_exception throwable -> throwable prim_stack = Panic.primitive_get_attached_stack_trace throwable stack_with_prims = Vector.Vector prim_stack - stack_with_prims.map Runtime_Extensions.wrap_primitive_stack_trace_element + stack_with_prims.map Runtime.wrap_primitive_stack_trace_element ## Takes any value, and if it is a dataflow error, throws it as a Panic, otherwise, returns the original value unchanged. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso index e37d86b227ed..f07bc5316291 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso @@ -23,4 +23,4 @@ type Function f (a = 2) = a * a f.call call : Any - call = @Builtin_Method "Function.call" \ No newline at end of file + call = @Builtin_Method "Function.call" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index ae36d4593038..9c15cfaee6f9 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -29,7 +29,10 @@ import project.Meta import project.Meta.Enso_Project import project.Polyglot import project.Polyglot.Java +import project.Runtime import project.Runtime.Extensions +import project.Runtime.State +import project.Runtime.Resource import project.System.Environment import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode @@ -51,6 +54,8 @@ export project.IO.Prim_Io export project.Math export project.Meta export project.Polyglot.Java +export project.Runtime +export project.Runtime.State export project.System.Environment export project.System.File export project.Data.Text.Regex.Mode as Regex_Mode @@ -81,5 +86,6 @@ from project.Meta.Enso_Project export all from project.Nothing export all from project.Polyglot export all from project.Runtime.Extensions export all +from project.Runtime.Resource export all -from Standard.Builtins export all hiding Less, Equal, Greater, Ordering +from Standard.Builtins export all diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso index 836a12680e11..679ce069300c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta.enso @@ -1,7 +1,5 @@ from Standard.Base import all -from Standard.Builtins import Any - ## UNSTABLE ADVANCED diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta/Enso_Project.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta/Enso_Project.enso index 35137147230f..481dc3b3e644 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Meta/Enso_Project.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Meta/Enso_Project.enso @@ -1,39 +1,49 @@ -from Standard.Base import all +import Standard.Base.System.File -import Standard.Builtins +## Functionality for inspecting the current project. +type Project_Description -## Returns the root directory of the project. + ## A representation of an Enso project. - > Example - Get the root directory of the project. + Arguments: + - prim_root_file: The primitive root file of the project. + - prim_config: The primitive config of the project. + @Builtin_Type + type Project_Description prim_root_file prim_config - Enso_Project.root -Builtins.Project_Description.root : File.File -Builtins.Project_Description.root = File.new this.prim_root_file.getPath -## Returns the root data directory of the project. + ## Returns the root directory of the project. - > Example - Get the data directory of the project. + > Example + Get the root directory of the project. - Enso_Project.data -Builtins.Project_Description.data : File.File -Builtins.Project_Description.data = this.root / "data" + Enso_Project.root + root : File.File + root = File.new this.prim_root_file.getPath -## Returns the name of the project. + ## Returns the root data directory of the project. - > Example - Get the name of the project. + > Example + Get the data directory of the project. - Enso_Project.name -Builtins.Project_Description.name : Text -Builtins.Project_Description.name = this.prim_config.name + Enso_Project.data + data : File.File + data = this.root / "data" -## Returns the namespace of the project. + ## Returns the name of the project. - > Example - Get the namespace of the project. + > Example + Get the name of the project. - Enso_Project.namespace -Builtins.Project_Description.namespace : Text -Builtins.Project_Description.namespace = this.prim_config.namespace + Enso_Project.name + name : Text + name = this.prim_config.name + + ## Returns the namespace of the project. + + > Example + Get the namespace of the project. + + Enso_Project.namespace + namespace : Text + namespace = this.prim_config.namespace diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso index f2d7a0715de7..9b24da3a2528 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso @@ -4,4 +4,4 @@ Option abstraction. The type a | Nothing is semantically equivalent to Maybe a. @Builtin_Type -type Nothing \ No newline at end of file +type Nothing diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso new file mode 100644 index 000000000000..1acf3cc05f96 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -0,0 +1,98 @@ +import Standard.Base.Data.Vector +import Standard.Base.Polyglot +import Standard.Base.Nothing +from Standard.Base.Runtime.Extensions import Source_Location + +## Utilities for interacting with the runtime. +##type Runtime +## +## ## A container type for utility methods that allow interacting with the Enso +## runtime. +## @Builtin_Type +## type Runtime + +## PRIVATE + + Returns a raw representation of the current execution stack trace. + You probably want `Runtime.get_stack_trace` instead. +primitive_get_stack_trace : Array +primitive_get_stack_trace = @Builtin_Method "Runtime.primitive_get_stack_trace" + +## ADVANCED + UNSTABLE + + Returns the execution stack trace of its call site. The ordering of the + resulting vector is such that the top stack frame is the first element. +get_stack_trace : Vector.Vector Stack_Trace_Element +get_stack_trace = + prim_stack = this.primitive_get_stack_trace + stack_with_prims = Vector.Vector prim_stack + stack = stack_with_prims.map here.wrap_primitive_stack_trace_element + # drop this frame and the one from `Runtime.primitive_get_stack_trace` + stack.drop_start 2 + +## ADVANCED + + Suggests that the runtime perform garbage collection. + + It is not _guaranteed_ to perform garbage collection, but in practice + will _usually_ begin a garbage collection cycle. + + > Example + Ask for the runtime to collect garbage. + + Runtime.gc +gc : Nothing +gc = @Builtin_Method "Runtime.gc" + +## ADVANCED + + Executes the provided action without allowing it to inline. + + Arguments: + - action: The computation to be executed. + + This is particularly useful when writing benchmarks and + performance-critical code where you need to prevent inlining from + occurring. + + > Example + Print something to the console without it being inlined. + + Runtime.no_inline <| IO.println "Hi!" +no_inline : Any -> Any +no_inline ~action = @Builtin_Method "Runtime.no_inline" + +## ADVANCED + UNSTABLE + + Applies the following function to the given argument, without allowing + them to inline. + + Arguments: + - function: The one-argument function to call. + - arg: The single argument for the function. + + This is particularly useful to avoid constant folding in benchmarks. + + > Example + Print something to the console without it being inlined. + + Runtime.no_inline_with_arg IO.println "Hi!" +no_inline_with_arg : Any -> Any +no_inline_with_arg function arg = @Builtin_Method "Runtime.no_inline_with_arg" + +## PRIVATE + Converts a primitive stack trace element into the regular one. +wrap_primitive_stack_trace_element el = + loc = if Polyglot.has_source_location el then (Source_Location (Polyglot.get_source_location el)) else Nothing + name = Polyglot.get_executable_name el + Stack_Trace_Element name loc + +## ADVANCED + UNSTABLE + + Represents a single stack frame in an Enso stack trace. +type Stack_Trace_Element + ## PRIVATE + type Stack_Trace_Element name source_location \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso new file mode 100644 index 000000000000..dedfa332b1c3 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso @@ -0,0 +1,36 @@ +## Debug utilities. +## A type on which debugging functionality is exposed. +@Builtin_Type +type Debug + +## TEXT_ONLY + + Places a breakpoint in the program's execution, dropping the user into an + interactive debugging REPL. + + From the REPL, the user is able to manipulate both the program state and + its execution in an interactive fashion. + + > Example + Dropping into a debugging REPL during execution. + + Debug.breakpoint +breakpoint : Nothing +breakpoint = @Builtin_Method "Debug.breakpoint" + +## Evaluates the provided Enso code in the caller frame. + + Arguments: + - expression: The enso code to evaluate. + + ? Scoping + The fact that expression is evaluated in the caller frame means that + it has access to variables in the scope enclosing the call to + Debug.eval. + + > Example + Evaluating the expression 1 + 1 and assigning it to a value. + + result = Debug.eval "1 + 1" +eval : Text -> Any +eval expression = @Builtin_Method "Debug.eval" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso index 083fab6d8f6f..f98184f80b3b 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Extensions.enso @@ -65,33 +65,3 @@ type Source_Location Return the source file corresponding to this location. file : File.File file = File.new this.prim_location.getSource.getPath - -## ADVANCED - UNSTABLE - - Represents a single stack frame in an Enso stack trace. -type Stack_Trace_Element - ## PRIVATE - type Stack_Trace_Element name source_location - -## ADVANCED - UNSTABLE - - Returns the execution stack trace of its call site. The ordering of the - resulting vector is such that the top stack frame is the first element. -Runtime.get_stack_trace : Vector.Vector Stack_Trace_Element -Runtime.get_stack_trace = - prim_stack = this.primitive_get_stack_trace - stack_with_prims = Vector.Vector prim_stack - stack = stack_with_prims.map here.wrap_primitive_stack_trace_element - # drop this frame and the one from `Runtime.primitive_get_stack_trace` - stack.drop_start 2 - -## PRIVATE - Converts a primitive stack trace element into the regular one. -wrap_primitive_stack_trace_element el = - loc = case Polyglot.has_source_location el of - True -> Source_Location (Polyglot.get_source_location el) - False -> Nothing - name = Polyglot.get_executable_name el - Stack_Trace_Element name loc diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso new file mode 100644 index 000000000000..6cceb0ad8ac7 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso @@ -0,0 +1,77 @@ +## An API for manual resource management. + +## Resource provides an API for manual management of computation resources. + + These include things like file handles, network sockets, and so on. This + API is intended for use by library developers to provide higher-level and + easier to use abstractions. + +## ADVANCED + + Acquires a resource, performs an action on it, and destroys it safely, + even in the presence of panics. + + Arguments: + - constructor: The computation responsible for acquiring the resource. + - destructor: The computation responsible for destroying the resource + once it is done being used. + - action: The computation to perform on the acquired resource. +bracket : Any -> (Any -> Nothing) -> (Any -> Any) -> Any +bracket ~constructor ~destructor ~action = @Builtin_Method "Resource.bracket" + +## An API for automatic resource management. +type Managed_Resource + + ## A managed resource is a special type of resource that is subject to + automated cleanup when it is no longer in use. + + This API is intended for use by developers to provide easy-to-use + abstractions, and is not expected to be used by end-users. + @Builtin_Type + type Managed_Resource + + ## ADVANCED + + Registers a resource with the resource manager to be cleaned up using + function once it is no longer in use. + + Arguments: + - resource: The resource to be managed automatically. + - function: The action to be executed on resource to clean it up when + it is no longer in use. + register : Any -> (Any -> Nothing) -> Managed_Resource + register resource function = @Builtin_Method "Managed_Resource.register" + + ## ADVANCED + + Forces finalization of a managed resource using the registered finalizer, + even if the resource is still reachable. + + Arguments: + - resource: The resource that should be finalized. + finalize : Managed_Resource -> Nothing + finalize resource = @Builtin_Method "Managed_Resource.finalize" + + ## ADVANCED + + Executes the provided action on the resource managed by the managed + resource object. + + Arguments: + - resource: The managed resource on which to run the action. + - action: The action that will be applied to the resource managed by + resource. + with : Managed_Resource -> (Any -> Any) -> Any + with resource ~action = @Builtin_Method "Managed_Resource.with" + + ## ADVANCED + + Takes the value held by the managed resource and unregisters the + finalization step for this resource, effectively removing it from the + managed resources system. + + Arguments: + - resource: The managed resource from which to acquire the underlying + resource. + take : Managed_Resource -> Any + take resource = @Builtin_Method "Managed_Resource.take" \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/State.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/State.enso new file mode 100644 index 000000000000..459a70d6575b --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/State.enso @@ -0,0 +1,52 @@ +## The runtime's integrated monadic state management. +## A container type for functionality for working with the runtime's + integrated state functionality. + +## Executes a stateful computation in a local state environment. + + Arguments: + - key: The key to associate your local_state with in the environment. + It is recommended that types be used as keys. + - local_state: The value to associate with key. + - computation: The computation to execute in the local state + environment. + + > Example + Print a value from the state. + + State.run Integer 0 <| IO.println (State.get Integer) +run : Any -> Any -> Any -> Any +run key local_state ~computation = @Builtin_Method "State.run" + +## Returns the current value for the provided key contained in the monadic + state. + + Arguments: + - key: The key into the state to get the associated value for. + + Returns an uninitialized state error if the user tries to read from an + uninitialized slot. + + > Example + Get the value of state for a key. + + State.get Decimal +get : Any -> Any ! Uninitialized_State +get key = @Builtin_Method "State.get" + +## Associates a new_state with the provided key in the runtime's monadic + state, returning the provided state. + + Arguments: + - key: The key with which to associate the new state. + - new_state: The new state to store. + + Returns an uninitialized state error if the user tries to read from an + uninitialized slot. + + > Example + Store a new value in the state for a given key. + + State.put Text 2821 +put : Any -> Any -> Any ! Uninitialized_State +put key new_state = @Builtin_Method "State.put" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Thread.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Thread.enso new file mode 100644 index 000000000000..40e61d761a97 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Thread.enso @@ -0,0 +1,19 @@ +## Utilities for working with threads. +## Internal threading utilities used for working with threads. + +## ADVANCED + + Executes an action with a handler for the executing thread being + interrupted. + + Arguments: + - action: The action to execute. + - interrupt_handler: The code to be executed if the thread is + interrupted. + + > Example + Die on thread interrupts. + + Thread.with_interrupt_handler (1 + 1) <| IO.println "I died!" +with_interrupt_handler : Any -> Any -> Any +with_interrupt_handler ~action ~interrupt_handler = @Builtin_Method "Thread.with_interrupt_handler" \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Unsafe.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Unsafe.enso new file mode 100644 index 000000000000..aa4c4e74e791 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Unsafe.enso @@ -0,0 +1,14 @@ +## Unsafe operations. + A container for unsafe operations that operate based on implementation + details of the language. + +## PRIVATE + + Sets the atom field at the provided index to have the provided value. + + Arguments: + - atom: The atom to set the field in. + - index: The index of the field to set (zero-based). + - value: The value to set the field at index to. +set_atom_field : Atom -> Integer -> Any -> Atom +set_atom_field atom index value = @Builtin_Method "Unsafe.set_atom_field" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso new file mode 100644 index 000000000000..b71580ca7676 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso @@ -0,0 +1,60 @@ +## Functionality for interacting with the host system. + +type System + +## PRIVATE + + Create a system process, returning the exit code, and the outputs to both + standard out and standard error. + + Arguments: + - command: The name of the system process. + - arguments: An array of arguments to the system process. + - input: The input to pass to the process via standard input. + - redirect_in: Specifies if the standard input of the program should be + redirected to the started process. + - redirect_out: Specifies if the standard output of the started process + should be redirected to the program's standard output. + - redirect_err: Specifies if the standard error output of the started + process should be redirected to the program's standard error output. +create_process : Text -> Array -> Text -> Boolean -> Boolean -> Boolean -> System_Process_Result +create_process command arguments input redirect_in redirect_out redirect_err = @Builtin_Method "System.create_process" + +## Exits the Enso program, returning the provided code to the parent + process. + + Arguments: + - code: The numerical exit code for the Enso program. + + > Example + Exit the enso program with a failure. + + System.exit 42 +exit : Integer -> Nothing +exit code = @Builtin_Method "System.exit" + +## Gets the nanosecond resolution system time at the moment of the call. + + > Example + Getting the current value of the nanosecond timer. + + System.nano_time +nano_time : Integer +nano_time = @Builtin_Method "System.nano_time" + +## PRIVATE + + Get the name of the current platform upon which the program is running. +os : Text +os = @Builtin_Method "System.os" + +## PRIVATE + + The type representing the result of a subprocess exiting. + + Arguments: + - exit_code: The exit code of the child process. + - stdout: Any values printed to standard out by the child process. + - stderr: Any values printed to standard error by the child process. +@Builtin_Type +type System_Process_Result exit_code stdout stderr \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso index d2ec6ac6f410..b9dc961ebce1 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso @@ -1,6 +1,7 @@ from Standard.Base import all import Standard.Base.System.File.Option +from Standard.Base.Runtime.Resource import all export Standard.Base.System.File.Option diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Platform.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Platform.enso index bff9c2b449d4..de2d4447123e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Platform.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Platform.enso @@ -1,6 +1,4 @@ -from Standard.Base import all - -from Standard.Builtins import System +import Standard.Base.System ## A representation of the various operating systems on which Enso can run. type Os diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process.enso index dcb1c682a4a2..8dd93c2dcf84 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process.enso @@ -1,9 +1,9 @@ from Standard.Base import all +import Standard.Base.System import Standard.Base.System.Process.Exit_Code from Standard.Base.Data.Vector import Vector -from Standard.Builtins import Array, System, True, False ## ALIAS Run a Command UNSTABLE @@ -128,4 +128,3 @@ type Builder - stdout: The contents of the process' standard output. - stderr: The contents of the process' standard error. type Result exit_code stdout stderr - diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso index e9f134c1869e..e5f9c4122480 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso @@ -1,4 +1,5 @@ from Standard.Base import all +from Standard.Base.Runtime import Stack_Trace_Element ## A representation of a dataflow warning attached to a value. type Warning diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection.enso index 9b299b585f46..03b3883af66d 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection.enso @@ -1,5 +1,7 @@ from Standard.Base import all +import Standard.Base.Runtime.Resource + import Standard.Database.Data.Dialect import Standard.Database.Data.Internal.IR import Standard.Database.Data.Sql diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso index 19b3ef91fde2..8e3962ad2b18 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso @@ -1,4 +1,5 @@ from Standard.Base import all +import Standard.Base.Runtime.Unsafe ## Creates a new Unique_Name_Strategy instance. diff --git a/distribution/lib/Standard/Test/0.0.0-dev/src/Bench.enso b/distribution/lib/Standard/Test/0.0.0-dev/src/Bench.enso index 1f462393ce64..2e290608d6c2 100644 --- a/distribution/lib/Standard/Test/0.0.0-dev/src/Bench.enso +++ b/distribution/lib/Standard/Test/0.0.0-dev/src/Bench.enso @@ -1,4 +1,5 @@ from Standard.Base import all +import Standard.Base.System ## Measure the amount of time it takes to execute a given computation. diff --git a/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso index ae7d5b8137ae..7f78c3bf9903 100644 --- a/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso @@ -1,4 +1,6 @@ from Standard.Base import all +import Standard.Base.Runtime.State +import Standard.Base.System import Standard.Builtins diff --git a/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala index b3f3d366bec7..05dcf156a81f 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala @@ -292,7 +292,7 @@ class UpgradeSpec val script = getTestDirectory / "script.enso" val message = "Hello from test" val content = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO |main = IO.println "$message" |""".stripMargin FileSystem.writeTextFile(script, content) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala index bc45ff826f67..3e0aebbb9447 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala @@ -7,7 +7,7 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOfromCallCode = """ - |from Standard.Builtins import all + |from Standard.Builtins import Number | |type Foo | diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala index d976cb5d8f44..74fc762ac422 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala @@ -49,7 +49,8 @@ class RecursionFixtures extends DefaultInterpreterRunner { val oversaturatedRecursiveCall = getMain(oversaturatedRecursiveCallTCOCode) val sumStateTCOCode = - """from Standard.Builtins import all + """from Standard.Builtins import Number + |import Standard.Base.Runtime.State | |stateSum = n -> | acc = State.get Number @@ -63,7 +64,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val sumStateTCO = getMain(sumStateTCOCode) val sumTCOWithEvalCode = - """from Standard.Builtins import all + """import Standard.Base.Runtime.Debug | |main = sumTo -> | summator = acc -> current -> @@ -75,7 +76,8 @@ class RecursionFixtures extends DefaultInterpreterRunner { val sumTCOWithEval = getMain(sumTCOWithEvalCode) val nestedThunkSumCode = - """from Standard.Builtins import all + """from Standard.Builtins import Number + |import Standard.Base.Runtime.State |import Standard.Base.Nothing | |doNTimes = n -> ~block -> diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java new file mode 100644 index 000000000000..7d83195ea9f5 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.meta; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; +@BuiltinType(params = "prim_root_file,prim_config") +public class ProjectDescription extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java new file mode 100644 index 000000000000..d5f018760849 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java @@ -0,0 +1,9 @@ +package org.enso.interpreter.node.expression.builtin.ordering; + +import org.enso.interpreter.node.expression.builtin.Builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +public class Equal extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java new file mode 100644 index 000000000000..3c86165121ef --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.ordering; +import org.enso.interpreter.node.expression.builtin.Builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +public class Greater extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java new file mode 100644 index 000000000000..31589bad3c0d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.ordering; +import org.enso.interpreter.node.expression.builtin.Builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +public class Less extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java new file mode 100644 index 000000000000..0d95814e0f6b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.ordering; +import org.enso.interpreter.node.expression.builtin.Builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +public class Ordering extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java new file mode 100644 index 000000000000..40fe2873f4e6 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.resource; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class ManagedResource extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java index 64ad08ae797a..ce65d0243deb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java @@ -115,9 +115,7 @@ Object doCreate( Text returnErr = Text.create(err.toString()); return ctx.getBuiltins() - .system() - .getSystemProcessResult() - .newInstance(exitCode, returnOut, returnErr); + .system().makeSystemResult(exitCode, returnOut, returnErr); } catch (IOException | InterruptedException e) { throw new PanicException(e.getMessage(), this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java new file mode 100644 index 000000000000..1baba8e00b9a --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.system; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType(params = "exit_code,stdout,stderr") +public class SystemProcessResult extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java index e9c04a335e34..61afb076676d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java @@ -469,16 +469,15 @@ private static Object evalExpression( ModuleScope scope, Object[] args, Context context, CallOptimiserNode callOptimiserNode) throws ArityException, UnsupportedTypeException { String expr = Types.extractArguments(args, String.class); - AtomConstructor debug = context.getBuiltins().debug(); - Function eval = - context - .getBuiltins() - .getScope() - .lookupMethodDefinition(debug, Builtins.MethodNames.Debug.EVAL); + Builtins builtins = context.getBuiltins(); + Function eval = builtins.getBuiltinFunction( + builtins.debug(), + Builtins.MethodNames.Debug.EVAL, + context.getLanguage()).orElseThrow(); CallerInfo callerInfo = new CallerInfo(null, LocalScope.root(), scope); Object state = context.getBuiltins().nothing().newInstance(); return callOptimiserNode - .executeDispatch(eval, callerInfo, state, new Object[] {debug, Text.create(expr)}) + .executeDispatch(eval, callerInfo, state, new Object[] {builtins.debug(), Text.create(expr)}) .getValue(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 539bd0effc11..361d52355ff4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -22,20 +22,11 @@ import org.enso.interpreter.node.expression.builtin.Boolean; import org.enso.interpreter.node.expression.builtin.bool.False; import org.enso.interpreter.node.expression.builtin.bool.True; -import org.enso.interpreter.node.expression.builtin.debug.DebugBreakpointMethodGen; -import org.enso.interpreter.node.expression.builtin.debug.DebugEvalMethodGen; +import org.enso.interpreter.node.expression.builtin.meta.ProjectDescription; import org.enso.interpreter.node.expression.builtin.mutable.Array; import org.enso.interpreter.node.expression.builtin.mutable.Ref; -import org.enso.interpreter.node.expression.builtin.runtime.GCMethodGen; -import org.enso.interpreter.node.expression.builtin.runtime.GetStackTraceMethodGen; -import org.enso.interpreter.node.expression.builtin.runtime.NoInlineMethodGen; -import org.enso.interpreter.node.expression.builtin.runtime.NoInlineWithArgMethodGen; -import org.enso.interpreter.node.expression.builtin.state.GetStateMethodGen; -import org.enso.interpreter.node.expression.builtin.state.PutStateMethodGen; -import org.enso.interpreter.node.expression.builtin.state.RunStateMethodGen; +import org.enso.interpreter.node.expression.builtin.resource.ManagedResource; import org.enso.interpreter.node.expression.builtin.text.Text; -import org.enso.interpreter.node.expression.builtin.thread.WithInterruptHandlerMethodGen; -import org.enso.interpreter.node.expression.builtin.unsafe.SetAtomFieldMethodGen; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; @@ -63,15 +54,16 @@ public static class Debug { private final Map>> builtinMethodNodes; private final Map builtins; - private final AtomConstructor debug; - private final AtomConstructor projectDescription; + @CompilerDirectives.CompilationFinal + private AtomConstructor debug; + @CompilerDirectives.CompilationFinal + private AtomConstructor projectDescription; private final Error error; private final Module module; private final ModuleScope scope; private final Number number; private final Ordering ordering; - private final Resource resource; private final System system; private final Special special; @@ -109,6 +101,9 @@ public static class Debug { @CompilerDirectives.CompilationFinal private AtomConstructor ref; + @CompilerDirectives.CompilationFinal + private AtomConstructor managedResource; + /** * Creates an instance with builtin methods installed. * @@ -125,59 +120,25 @@ public Builtins(Context context) { registerBuiltinMethods(builtinTypes, scope, language); error = new Error(this); + ordering = new Ordering(this); + system = new System(this); // TODO: Builtins that are not yet moved to stdlib - debug = new AtomConstructor("Debug", scope).initializeFields(); Warning.initWarningMethods(language, scope); - projectDescription = - new AtomConstructor("Project_Description", scope) - .initializeFields( - new ArgumentDefinition( - 0, "prim_root_file", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "prim_config", ArgumentDefinition.ExecutionMode.EXECUTE)); - number = new Number(language, scope); - ordering = new Ordering(language, scope); - resource = new Resource(language, scope); - system = new System(language, scope); special = new Special(language); - - AtomConstructor runtime = new AtomConstructor("Runtime", scope).initializeFields(); - AtomConstructor state = new AtomConstructor("State", scope).initializeFields(); - - AtomConstructor thread = new AtomConstructor("Thread", scope).initializeFields(); - - AtomConstructor unsafe = new AtomConstructor("Unsafe", scope).initializeFields(); - - scope.registerConstructor(state); - scope.registerConstructor(debug); - scope.registerConstructor(projectDescription); - scope.registerConstructor(runtime); - scope.registerConstructor(thread); - - scope.registerConstructor(unsafe); - - scope.registerMethod(runtime, "no_inline", NoInlineMethodGen.makeFunction(language)); - scope.registerMethod( - runtime, "no_inline_with_arg", NoInlineWithArgMethodGen.makeFunction(language)); - scope.registerMethod(runtime, "gc", GCMethodGen.makeFunction(language)); - scope.registerMethod( - runtime, "primitive_get_stack_trace", GetStackTraceMethodGen.makeFunction(language)); - - scope.registerMethod(state, "get", GetStateMethodGen.makeFunction(language)); - scope.registerMethod(state, "put", PutStateMethodGen.makeFunction(language)); - scope.registerMethod(state, "run", RunStateMethodGen.makeFunction(language)); - - scope.registerMethod(debug, MethodNames.Debug.EVAL, DebugEvalMethodGen.makeFunction(language)); - scope.registerMethod(debug, "breakpoint", DebugBreakpointMethodGen.makeFunction(language)); - - scope.registerMethod( - thread, "with_interrupt_handler", WithInterruptHandlerMethodGen.makeFunction(language)); - - scope.registerMethod(unsafe, "set_atom_field", SetAtomFieldMethodGen.makeFunction(language)); } - public void registerBuiltinMethods(List builtins, ModuleScope scope, Language language) { + /** + * Registers builtin methods with their corresponding Atom Constructor's owners. + * That way "special" builtin types have builtin methods in the scope without requiring + * everyone to always import full stdlib + * + * @param builtins List of Builtin Types + * @param scope Builtins scope + * @param language The language the resulting function nodes should be associated with + */ + private void registerBuiltinMethods(List builtins, ModuleScope scope, Language language) { for (AtomConstructor atom: builtins) { String tpeName = atom.getName(); this.builtins.put(tpeName, atom); @@ -236,6 +197,16 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) } } + /** + * Returns a list of supported builtins. + * + * Builtin types are marked via @BuiltinType annotation. THe metdata file represents a single + * builtin type per row. The format of the row is as follows: + * ::[,,...] + * where the last column gives a list of optional type's fields. + * + * @param scope Builtins scope + */ private List readBuiltinTypesMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; @@ -270,6 +241,16 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { }).filter(b -> b != null).collect(Collectors.toList()); } + /** + * Returns a Map of builtin method nodes. + * + * Builtin types are marked via @BuiltinMethod annotation. THe metdata file represents a single + * builtin method per row. The format of the row is as follows: + * : + * + * @param scope Builtins scope + * @return A map of builtin method nodes per builtin type name + */ private Map>> readBuiltinMethodsMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; @@ -318,6 +299,15 @@ private Map>> readBuiltinMethodsMetad return methodNodes; } + /** + * Returns a builtin method for the provided Atom Constructor and the name, if it exists. + * + * @param atom Atom Constructor owner of the function + * @param methodName Name of the method + * @param language The language the resulting function nodes should be associated with + * @return A non-empty function under the given name, if it exists. An empty value if no such builtin method was ever registerd + */ + public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone Map> atomNodes = builtinMethodNodes.get(atom.getName()); @@ -419,6 +409,15 @@ public AtomConstructor falseAtom() { return falseConstructor; } + /** @return the ManagedResource constructor. */ + private AtomConstructor managedResource() { + if (managedResource == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + managedResource = getBuiltinType(ManagedResource.class); + } + return managedResource; + } + /** @return the builtin Error types container. */ public Error error() { @@ -440,15 +439,24 @@ public AtomConstructor any() { /** * Returns the {@code Debug} atom constructor. + * TODO: this is redundant, figure out a way to avoid createing spurious Debug builtin type * * @return the {@code Debug} atom constructor */ public AtomConstructor debug() { + if (debug == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + debug = getBuiltinType(Debug.class); + } return debug; } - /** @return the {@code Enso_Project} atom constructor */ + /** @return the {@code Project_Description} atom constructor */ public AtomConstructor getProjectDescription() { + if (projectDescription == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + projectDescription = getBuiltinType(ProjectDescription.class); + } return projectDescription; } @@ -549,7 +557,7 @@ public Atom fromTypeSystem(String typeName) { case Constants.INTEGER: return number.getInteger().newInstance(); case Constants.MANAGED_RESOURCE: - return resource.getManagedResource().newInstance(); + return managedResource().newInstance(); case Constants.NOTHING: return nothing().newInstance(); case Constants.NUMBER: diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java new file mode 100644 index 000000000000..fc5e19f4b1d3 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.runtime.builtin; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class Debug extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java index 53079322dd80..eadff71a8b1e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java @@ -1,26 +1,36 @@ package org.enso.interpreter.runtime.builtin; +import com.oracle.truffle.api.CompilerDirectives; import org.enso.interpreter.Language; +import org.enso.interpreter.node.expression.builtin.error.UninitializedState; +import org.enso.interpreter.node.expression.builtin.ordering.Equal; +import org.enso.interpreter.node.expression.builtin.ordering.Greater; +import org.enso.interpreter.node.expression.builtin.ordering.Less; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; /** A container for builtin ordering types. */ public class Ordering { - private final AtomConstructor ordering; - private final AtomConstructor less; - private final AtomConstructor equal; - private final AtomConstructor greater; - - public Ordering(Language language, ModuleScope scope) { - ordering = new AtomConstructor("Ordering", scope).initializeFields(); - less = new AtomConstructor("Less", scope).initializeFields(); - equal = new AtomConstructor("Equal", scope).initializeFields(); - greater = new AtomConstructor("Greater", scope).initializeFields(); - scope.registerConstructor(ordering); - scope.registerConstructor(less); - scope.registerConstructor(equal); - scope.registerConstructor(greater); + + @CompilerDirectives.CompilationFinal + private AtomConstructor ordering; + + @CompilerDirectives.CompilationFinal + private AtomConstructor less; + + @CompilerDirectives.CompilationFinal + private AtomConstructor equal; + + @CompilerDirectives.CompilationFinal + private AtomConstructor greater; + + @CompilerDirectives.CompilationFinal + private Builtins builtins; + + + public Ordering(Builtins builtins) { + this.builtins = builtins; } /** @@ -41,36 +51,52 @@ public Atom fromJava(int ord) { /** @return a new instance of Less */ public Atom newLess() { - return less.newInstance(); + return less().newInstance(); } /** @return a new instance of Equal */ public Atom newEqual() { - return equal.newInstance(); + return equal().newInstance(); } /** @return a new instance of Greater */ public Atom newGreater() { - return greater.newInstance(); + return greater().newInstance(); } /** @return the Ordering constructor. */ public AtomConstructor ordering() { + if (ordering == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + ordering = builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); + } return ordering; } /** @return the Less constructor */ public AtomConstructor less() { + if (less == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + less = builtins.getBuiltinType(Less.class); + } return less; } /** @return the Equal constructor */ public AtomConstructor equal() { + if (equal == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + equal = builtins.getBuiltinType(Equal.class); + } return equal; } /** @return the Greater constructor */ public AtomConstructor greater() { + if (greater == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + greater = builtins.getBuiltinType(Greater.class); + } return greater; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Resource.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Resource.java deleted file mode 100644 index ab4ca5bfaa08..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Resource.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.resource.*; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -/** Container for builtin Managed_Resource types */ -public class Resource { - private final AtomConstructor managedResource; - - /** - * Creates and registers the relevant constructors. - * - * @param language the current language instance. - * @param scope the scope to register constructors in. - */ - public Resource(Language language, ModuleScope scope) { - managedResource = new AtomConstructor("Managed_Resource", scope).initializeFields(); - scope.registerConstructor(managedResource); - AtomConstructor resource = new AtomConstructor("Resource", scope).initializeFields(); - scope.registerConstructor(resource); - scope.registerMethod(resource, "bracket", BracketMethodGen.makeFunction(language)); - scope.registerMethod(managedResource, "register", RegisterMethodGen.makeFunction(language)); - scope.registerMethod(managedResource, "with", WithMethodGen.makeFunction(language)); - scope.registerMethod(managedResource, "take", TakeMethodGen.makeFunction(language)); - scope.registerMethod(managedResource, "finalize", FinalizeMethodGen.makeFunction(language)); - } - - /** @return the managed resource atom constructor. */ - public AtomConstructor getManagedResource() { - return managedResource; - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java index 515a1969164c..4e1d16c64689 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java @@ -1,19 +1,19 @@ package org.enso.interpreter.runtime.builtin; +import com.oracle.truffle.api.CompilerDirectives; import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.system.CreateProcessMethodGen; -import org.enso.interpreter.node.expression.builtin.system.ExitMethodGen; -import org.enso.interpreter.node.expression.builtin.system.NanoTimeMethodGen; -import org.enso.interpreter.node.expression.builtin.system.OsMethodGen; +import org.enso.interpreter.node.expression.builtin.system.*; import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; +import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; /** A container class for all System-related stdlib builtins. */ public class System { - private final AtomConstructor system; - private final AtomConstructor systemProcessResult; + private AtomConstructor system; + private AtomConstructor systemProcessResult; + private final Builtins builtins; /** * Create and register all {@code System} constructors. @@ -21,30 +21,16 @@ public class System { * @param language the current language instance. * @param scope the scope to register constructors and methods in. */ - public System(Language language, ModuleScope scope) { - system = new AtomConstructor("System", scope).initializeFields(); - scope.registerConstructor(system); - systemProcessResult = - new AtomConstructor("System_Process_Result", scope) - .initializeFields( - new ArgumentDefinition(0, "exit_code", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(1, "stdout", ArgumentDefinition.ExecutionMode.EXECUTE), - new ArgumentDefinition(2, "stderr", ArgumentDefinition.ExecutionMode.EXECUTE)); - scope.registerConstructor(systemProcessResult); - - scope.registerMethod(system, "create_process", CreateProcessMethodGen.makeFunction(language)); - scope.registerMethod(system, "nano_time", NanoTimeMethodGen.makeFunction(language)); - scope.registerMethod(system, "exit", ExitMethodGen.makeFunction(language)); - scope.registerMethod(system, "os", OsMethodGen.makeFunction(language)); - } - - /** @return the atom constructor for {@code System}. */ - public AtomConstructor getSystem() { - return system; + public System(Builtins builtins) { + this.builtins = builtins; } /** @return the atom constructor for {@code Process_Result}. */ - public AtomConstructor getSystemProcessResult() { - return systemProcessResult; + public Atom makeSystemResult(Object exitCode, Object stdout, Object stderr) { + if (systemProcessResult == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + systemProcessResult = builtins.getBuiltinType(SystemProcessResult.class); + } + return systemProcessResult.newInstance(exitCode, stdout, stderr); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index e6855c3d1d0a..c176330f582a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -53,6 +53,14 @@ public AtomConstructor(String name, ModuleScope definitionScope) { this(name, definitionScope, false); } + /** + * Creates a new Atom constructor for a given name. The constructor is not valid until {@link + * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} is called. + * + * @param name the name of the Atom constructor + * @param definitionScope the scope in which this constructor was defined + * @param builtin if true, the constructor refers to a builtin type (annotated with @BuiltinType + */ public AtomConstructor(String name, ModuleScope definitionScope, Boolean builtin) { this.name = name; this.definitionScope = definitionScope; diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 4ab9a726e10f..567e590b929d 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -4,45 +4,6 @@ # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. -## Debug utilities. -type Debug - - ## A type on which debugging functionality is exposed. - @Builtin_Type - type Debug - - ## TEXT_ONLY - - Places a breakpoint in the program's execution, dropping the user into an - interactive debugging REPL. - - From the REPL, the user is able to manipulate both the program state and - its execution in an interactive fashion. - - > Example - Dropping into a debugging REPL during execution. - - Debug.breakpoint - breakpoint : Nothing - breakpoint = @Builtin_Method "Debug.breakpoint" - - ## Evaluates the provided Enso code in the caller frame. - - Arguments: - - expression: The enso code to evaluate. - - ? Scoping - The fact that expression is evaluated in the caller frame means that - it has access to variables in the scope enclosing the call to - Debug.eval. - - > Example - Evaluating the expression 1 + 1 and assigning it to a value. - - result = Debug.eval "1 + 1" - eval : Text -> Any - eval expression = @Builtin_Method "Debug.eval" - @Builtin_Type type Prim_Warning type Prim_Warning @@ -737,354 +698,3 @@ type Decimal 5.0.to_decimal to_decimal : Decimal to_decimal = @Builtin_Method "Decimal.to_decimal" - -## An API for manual resource management. -type Resource - - ## Resource provides an API for manual management of computation resources. - - These include things like file handles, network sockets, and so on. This - API is intended for use by library developers to provide higher-level and - easier to use abstractions. - @Builtin_Type - type Resource - - ## ADVANCED - - Acquires a resource, performs an action on it, and destroys it safely, - even in the presence of panics. - - Arguments: - - constructor: The computation responsible for acquiring the resource. - - destructor: The computation responsible for destroying the resource - once it is done being used. - - action: The computation to perform on the acquired resource. - bracket : Any -> (Any -> Nothing) -> (Any -> Any) -> Any - bracket ~constructor ~destructor ~action = - @Builtin_Method "Resource.bracket" - -## An API for automatic resource management. -type Managed_Resource - - ## A managed resource is a special type of resource that is subject to - automated cleanup when it is no longer in use. - - This API is intended for use by developers to provide easy-to-use - abstractions, and is not expected to be used by end-users. - @Builtin_Type - type Managed_Resource - - ## ADVANCED - - Registers a resource with the resource manager to be cleaned up using - function once it is no longer in use. - - Arguments: - - resource: The resource to be managed automatically. - - function: The action to be executed on resource to clean it up when - it is no longer in use. - register : Any -> (Any -> Nothing) -> Managed_Resource - register resource function = @Builtin_Method "Managed_Resource.register" - - ## ADVANCED - - Forces finalization of a managed resource using the registered finalizer, - even if the resource is still reachable. - - Arguments: - - resource: The resource that should be finalized. - finalize : Managed_Resource -> Nothing - finalize resource = @Builtin_Method "Managed_Resource.finalize" - - ## ADVANCED - - Executes the provided action on the resource managed by the managed - resource object. - - Arguments: - - resource: The managed resource on which to run the action. - - action: The action that will be applied to the resource managed by - resource. - with : Managed_Resource -> (Any -> Any) -> Any - with resource ~action = @Builtin_Method "Managed_Resource.with" - - ## ADVANCED - - Takes the value held by the managed resource and unregisters the - finalization step for this resource, effectively removing it from the - managed resources system. - - Arguments: - - resource: The managed resource from which to acquire the underlying - resource. - take : Managed_Resource -> Any - take resource = @Builtin_Method "Managed_Resource.take" - -## Utilities for interacting with the runtime. -type Runtime - - ## A container type for utility methods that allow interacting with the Enso - runtime. - @Builtin_Type - type Runtime - - ## ADVANCED - - Suggests that the runtime perform garbage collection. - - It is not _guaranteed_ to perform garbage collection, but in practice - will _usually_ begin a garbage collection cycle. - - > Example - Ask for the runtime to collect garbage. - - Runtime.gc - gc : Nothing - gc = @Builtin_Method "Runtime.gc" - - ## ADVANCED - - Executes the provided action without allowing it to inline. - - Arguments: - - action: The computation to be executed. - - This is particularly useful when writing benchmarks and - performance-critical code where you need to prevent inlining from - occurring. - - > Example - Print something to the console without it being inlined. - - Runtime.no_inline <| IO.println "Hi!" - no_inline : Any -> Any - no_inline ~action = @Builtin_Method "Runtime.no_inline" - - ## ADVANCED - UNSTABLE - - Applies the following function to the given argument, without allowing - them to inline. - - Arguments: - - function: The one-argument function to call. - - arg: The single argument for the function. - - This is particularly useful to avoid constant folding in benchmarks. - - > Example - Print something to the console without it being inlined. - - Runtime.no_inline_with_arg IO.println "Hi!" - no_inline_with_arg : Any -> Any - no_inline_with_arg function arg = @Builtin_Method "Runtime.no_inline_with_arg" - - ## PRIVATE - - Returns a raw representation of the current execution stack trace. - You probably want `Runtime.get_stack_trace` instead. - primitive_get_stack_trace : Array - primitive_get_stack_trace = @Builtin_Method "Runtime.primitive_get_stack_trace" - - - -## The runtime's integrated monadic state management. -type State - - ## A container type for functionality for working with the runtime's - integrated state functionality. - @Builtin_Type - type State - - ## Executes a stateful computation in a local state environment. - - Arguments: - - key: The key to associate your local_state with in the environment. - It is recommended that types be used as keys. - - local_state: The value to associate with key. - - computation: The computation to execute in the local state - environment. - - > Example - Print a value from the state. - - State.run Integer 0 <| IO.println (State.get Integer) - run : Any -> Any -> Any -> Any - run key local_state ~computation = @Builtin_Method "State.run" - - ## Returns the current value for the provided key contained in the monadic - state. - - Arguments: - - key: The key into the state to get the associated value for. - - Returns an uninitialized state error if the user tries to read from an - uninitialized slot. - - > Example - Get the value of state for a key. - - State.get Decimal - get : Any -> Any ! Uninitialized_State - get key = @Builtin_Method "State.get" - - ## Associates a new_state with the provided key in the runtime's monadic - state, returning the provided state. - - Arguments: - - key: The key with which to associate the new state. - - new_state: The new state to store. - - Returns an uninitialized state error if the user tries to read from an - uninitialized slot. - - > Example - Store a new value in the state for a given key. - - State.put Text 2821 - put : Any -> Any -> Any ! Uninitialized_State - put key new_state = @Builtin_Method "State.put" - -## Functionality for interacting with the host system. -type System - - ## A container type for functionality that allows the runtime to talk to - the host system. - @Builtin_Type - type System - - ## PRIVATE - - Create a system process, returning the exit code, and the outputs to both - standard out and standard error. - - Arguments: - - command: The name of the system process. - - arguments: An array of arguments to the system process. - - input: The input to pass to the process via standard input. - - redirect_in: Specifies if the standard input of the program should be - redirected to the started process. - - redirect_out: Specifies if the standard output of the started process - should be redirected to the program's standard output. - - redirect_err: Specifies if the standard error output of the started - process should be redirected to the program's standard error output. - create_process : Text -> Array -> Text -> Boolean -> Boolean -> Boolean -> System_Process_Result - create_process command arguments input redirect_in redirect_out redirect_err = - @Builtin_Method "System.create_process" - - ## Exits the Enso program, returning the provided code to the parent - process. - - Arguments: - - code: The numerical exit code for the Enso program. - - > Example - Exit the enso program with a failure. - - System.exit 42 - exit : Integer -> Nothing - exit code = @Builtin_Method "System.exit" - - ## Gets the nanosecond resolution system time at the moment of the call. - - > Example - Getting the current value of the nanosecond timer. - - System.nano_time - nano_time : Integer - nano_time = @Builtin_Method "System.nano_time" - - ## PRIVATE - - Get the name of the current platform upon which the program is running. - os : Text - os = @Builtin_Method "System.os" - -## PRIVATE - - The type representing the result of a subprocess exiting. - - Arguments: - - exit_code: The exit code of the child process. - - stdout: Any values printed to standard out by the child process. - - stderr: Any values printed to standard error by the child process. -@Builtin_Type -type System_Process_Result exit_code stdout stderr - - -## Utilities for working with threads. -type Thread - - ## Internal threading utilities used for working with threads. - @Builtin_Type - type Thread - - ## ADVANCED - - Executes an action with a handler for the executing thread being - interrupted. - - Arguments: - - action: The action to execute. - - interrupt_handler: The code to be executed if the thread is - interrupted. - - > Example - Die on thread interrupts. - - Thread.with_interrupt_handler (1 + 1) <| IO.println "I died!" - with_interrupt_handler : Any -> Any -> Any - with_interrupt_handler ~action ~interrupt_handler = - @Builtin_Method "Thread.with_interrupt_handler" - -## Unsafe operations. -type Unsafe - - ## PRIVATE - - A container for unsafe operations that operate based on implementation - details of the language. - @Builtin_Method - type Unsafe - - ## PRIVATE - - Sets the atom field at the provided index to have the provided value. - - Arguments: - - atom: The atom to set the field in. - - index: The index of the field to set (zero-based). - - value: The value to set the field at index to. - set_atom_field : Atom -> Integer -> Any -> Atom - set_atom_field atom index value = @Builtin_Method "Unsafe.set_atom_field" - -## Functionality for inspecting the current project. -type Project_Description - - ## A representation of an Enso project. - - Arguments: - - prim_root_file: The primitive root file of the project. - @Builtin_Type - type Project_Description prim_root_file - -## A representation of the relative ordering between two values. -type Ordering - - ## A representation of the relative ordering between two values. - - These values must be able to be ordered with respect to each other. - @Builtin_Type - type Ordering - - ## A representation that the first value orders as less than the second. - @Builtin_Type - type Less - - ## A representation that the first value orders as equal to the second. - @Builtin_Type - type Equal - - ## A representation that the first value orders as greater than the second. - @Builtin_Type - type Greater diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 7723a4d7f304..6137a0be4b25 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -19,7 +19,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "initialize properly" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = Debug.breakpoint |""".stripMargin @@ -30,7 +30,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "be able to execute arbitrary code in the caller scope" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 1 @@ -50,7 +50,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "return the last evaluated value back to normal execution flow" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | a = 5 @@ -68,7 +68,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "be able to define its local variables" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -86,7 +86,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "not overwrite bindings" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -103,7 +103,9 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "access and modify monadic state" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug + |import Standard.Base.Runtime.State + |from Standard.Builtins import Number | |run = | State.put Number 10 @@ -123,7 +125,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "be able to list local variables in its scope" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -149,7 +151,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "be able to list bindings it has created" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -176,7 +178,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "allow to be nested" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | 10 * Debug.breakpoint + 1 @@ -199,7 +201,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "behave well when nested" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 1 @@ -226,7 +228,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "handle errors gracefully" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | Debug.breakpoint @@ -246,7 +248,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "attach language stack traces to the exception" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug |from Standard.Base.Error.Common import Panic | |main = @@ -273,7 +275,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { "not pollute bindings upon nested error" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | Debug.breakpoint diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index b166f9a03111..84637d25f3c8 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -156,13 +156,11 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val mainBody = metadata.addItem(42, 14) + val mainBody = metadata.addItem(7, 14) val code = - """from Standard.Builtins import all - | - |main = "Hello World!" - |""".stripMargin.linesIterator.mkString("\n") + """|main = "Hello World!" + |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) val mainFile = context.writeMain(contents) @@ -384,16 +382,14 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val mainBody = metadata.addItem(41, 28) - val fExpr = metadata.addItem(50, 10) + val mainBody = metadata.addItem(6, 28) + val fExpr = metadata.addItem(15, 10) // f body - metadata.addItem(55, 5) - val mainResExpr = metadata.addItem(65, 4) + metadata.addItem(20, 5) + val mainResExpr = metadata.addItem(30, 4) val code = - """from Standard.Builtins import all - | - |main = + """main = | f = x -> x + 1 | f 42 |""".stripMargin.linesIterator.mkString("\n") @@ -442,14 +438,12 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val fExpr = metadata.addItem(50, 5) - val xExpr = metadata.addItem(64, 4) - val mainResExpr = metadata.addItem(73, 1) + val fExpr = metadata.addItem(15, 5) + val xExpr = metadata.addItem(29, 4) + val mainResExpr = metadata.addItem(38, 1) val code = - """from Standard.Builtins import all - | - |main = + """main = | f = _ + 1 | x = f 42 | x @@ -499,14 +493,13 @@ class RuntimeInstrumentTest val metadata = new Metadata // f expression - metadata.addItem(41, 5) - val xExpr = metadata.addItem(63, 8) - val mainRes = metadata.addItem(76, 1) - val mainExpr = metadata.addItem(54, 23) + metadata.addItem(7, 5) + val xExpr = metadata.addItem(29, 8) + val mainRes = metadata.addItem(42, 1) + val mainExpr = metadata.addItem(20, 23) val code = - """from Standard.Builtins import all - | + """ |f x = x + 1 | |main = @@ -741,12 +734,12 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xExpr = metadata.addItem(49, 33) + val xExpr = metadata.addItem(14, 33) // function body - metadata.addItem(64, 5) + metadata.addItem(29, 5) // x result - metadata.addItem(78, 4) - val mainRes = metadata.addItem(87, 1) + metadata.addItem(43, 4) + val mainRes = metadata.addItem(52, 1) val code = """from Standard.Builtins import all @@ -801,19 +794,17 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xExpr = metadata.addItem(49, 36) + val xExpr = metadata.addItem(14, 36) // lambda - metadata.addItem(62, 10) + metadata.addItem(27, 10) // lambda body - metadata.addItem(67, 5) + metadata.addItem(32, 5) // x result - metadata.addItem(81, 4) - val mainRes = metadata.addItem(90, 1) + metadata.addItem(46, 4) + val mainRes = metadata.addItem(55, 1) val code = - """from Standard.Builtins import all - | - |main = + """main = | x = | f = x -> x + 1 | f 42 @@ -863,17 +854,15 @@ class RuntimeInstrumentTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val xExpr = metadata.addItem(49, 31) + val xExpr = metadata.addItem(14, 31) // lambda - metadata.addItem(62, 5) + metadata.addItem(27, 5) // x result - metadata.addItem(76, 4) - val mainRes = metadata.addItem(85, 1) + metadata.addItem(41, 4) + val mainRes = metadata.addItem(50, 1) val code = - """from Standard.Builtins import all - | - |main = + """main = | x = | f = _ + 1 | f 42 @@ -923,24 +912,23 @@ class RuntimeInstrumentTest val metadata = new Metadata // body of id method - metadata.addItem(51, 1) + metadata.addItem(17, 1) // body of id1 function - metadata.addItem(87, 3) + metadata.addItem(53, 3) // default lambda argument a->a in id method - metadata.addItem(43, 4) + metadata.addItem(9, 4) // default lambda argument a->a in id1 function - metadata.addItem(79, 4) + metadata.addItem(45, 4) // first x->x argument - metadata.addItem(103, 4) + metadata.addItem(79, 4) // second x->x argument - metadata.addItem(157, 4) - val arg1 = metadata.addItem(99, 2) - val arg2 = metadata.addItem(110, 2) - val arg3 = metadata.addItem(142, 2) + metadata.addItem(123, 4) + val arg1 = metadata.addItem(65, 2) + val arg2 = metadata.addItem(76, 2) + val arg3 = metadata.addItem(108, 2) val code = - """from Standard.Builtins import all - | + """ |id (x = a->a) = x | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 337d79099fa4..7c70f0f4f2cb 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -732,12 +732,13 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(66, 41) - val idMainBar = metadata.addItem(98, 8) + val idMain = metadata.addItem(101, 41) + val idMainBar = metadata.addItem(133, 8) val code = """from Standard.Builtins import all |import Standard.Base.IO + |import Standard.Base.Runtime.State | |main = IO.println (State.run Number 42 this.bar) | @@ -792,12 +793,13 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(66, 40) - val idMainBar = metadata.addItem(97, 8) + val idMain = metadata.addItem(101, 40) + val idMainBar = metadata.addItem(132, 8) val code = """from Standard.Builtins import all |import Standard.Base.IO + |import Standard.Base.Runtime.State | |main = IO.println (State.run Number 0 this.bar) | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index 175bbfc4900e..3ac9ea9d6506 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala @@ -37,7 +37,6 @@ class CompileDiagnosticsTest extends InterpreterTest { "surface redefinition errors in the language" in { val code = """from Standard.Base.Error.Common import all - |from Standard.Builtins import Nothing | |foo = | x = 1 @@ -51,7 +50,6 @@ class CompileDiagnosticsTest extends InterpreterTest { "surface non-existent variable errors in the language" in { val code = """from Standard.Base.Error.Common import all - |from Standard.Builtins import Nothing | |foo = | my_var = 10 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala index fa2c871f1b5e..eb957cf0476d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala @@ -11,7 +11,7 @@ class EvalTest extends InterpreterTest { "evaluate a string expression" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.Runtime.Debug |import Standard.Base.IO | |main = @@ -24,7 +24,7 @@ class EvalTest extends InterpreterTest { "have access to the caller scope" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.Runtime.Debug |import Standard.Base.IO | |main = @@ -38,7 +38,7 @@ class EvalTest extends InterpreterTest { "have access to the caller module scope" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.Runtime.Debug |import Standard.Base.IO | |type MyType x @@ -54,7 +54,7 @@ class EvalTest extends InterpreterTest { "return a value usable in the caller scope" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.Debug | |main = | x = 1 @@ -68,7 +68,7 @@ class EvalTest extends InterpreterTest { "work in a recursive setting" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.Debug | |main = | fn = sumTo -> @@ -82,7 +82,7 @@ class EvalTest extends InterpreterTest { "work inside a thunk passed to another function" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.Debug | |main = | fn = sumTo -> diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala index 47cf1fc6f1a9..46cb270403fc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala @@ -21,7 +21,7 @@ class RuntimeManagementTest extends InterpreterTest { .asHostObject[Context]() val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.Thread |from Standard.Base.IO import all |import Standard.Base.Nothing | @@ -77,7 +77,7 @@ class RuntimeManagementTest extends InterpreterTest { "Automatically free managed resources" in { val code = """ - |from Standard.Builtins import all + |from Standard.Base.Runtime.Resource import Managed_Resource |from Standard.Base.IO import all | |type Mock_File i @@ -116,7 +116,7 @@ class RuntimeManagementTest extends InterpreterTest { "Automatically free managed resources amongst manual closure of other managed resources" in { val code = """ - |from Standard.Builtins import all + |from Standard.Base.Runtime.Resource import Managed_Resource |from Standard.Base.IO import all |import Standard.Base.Nothing | @@ -157,7 +157,7 @@ class RuntimeManagementTest extends InterpreterTest { "Automatically free managed resources amongst manual takeover of other managed resources" in { val code = """ - |from Standard.Builtins import all + |from Standard.Base.Runtime.Resource import Managed_Resource |from Standard.Base.IO import all |import Standard.Base.Nothing | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index a9dc4ffb6706..2ab2a40d156c 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -11,7 +11,8 @@ class StateTest extends InterpreterTest { "be accessible from functions" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State + |from Standard.Builtins import Number | |stateful = | State.put Number 10 @@ -27,7 +28,8 @@ class StateTest extends InterpreterTest { "be implicitly threaded through function executions" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State + |from Standard.Builtins import Number | |inc_state = | x = State.get Number @@ -49,7 +51,8 @@ class StateTest extends InterpreterTest { "work well with recursive code" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State + |from Standard.Builtins import Number | |main = | stateSum = n -> @@ -64,10 +67,11 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Builtins import State,Number + """from Standard.Builtins import Number |from Standard.Base.Data.List import Nil |import Standard.Base.IO |import Standard.Base.Nothing + |import Standard.Base.Runtime.State | |run = | matcher = x -> case x of @@ -94,6 +98,7 @@ class StateTest extends InterpreterTest { "undo changes on Panics" in { val code = """from Standard.Base import all + |import Standard.Base.Runtime.State | |panicker = | State.put Number 400 @@ -111,7 +116,8 @@ class StateTest extends InterpreterTest { "localize properly with State.run when 1 key used" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State + |from Standard.Builtins import Number | |inner = State.put Number 0 | @@ -127,7 +133,7 @@ class StateTest extends InterpreterTest { "localize properly with State.run when 2 states used" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State | |type S1 |type S2 @@ -149,7 +155,7 @@ class StateTest extends InterpreterTest { "localize properly with State.run when multiple states used" in { val code = - """from Standard.Builtins import all + """import Standard.Base.Runtime.State | |type S1 |type S2 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index 95fe1b2279e3..79f88273d787 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -18,7 +18,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return success exit code (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -33,7 +33,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return success exit code (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -48,7 +48,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error when creating nonexistent command" in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all |main = System.create_process "nonexistentcommandxyz" Array.empty "" False False False @@ -62,7 +62,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error exit code (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -78,7 +78,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return error exit code (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -94,7 +94,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin chars (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -111,7 +111,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin chars (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -129,7 +129,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin bytes (Unix)" taggedAs OsUnix in { val input = Random.nextBytes(Byte.MaxValue) val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -146,7 +146,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin unused (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -163,7 +163,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin unused (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -180,7 +180,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin empty (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -196,7 +196,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdin empty (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -212,7 +212,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "provide stdin string (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -228,7 +228,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "provide stdin string (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -244,7 +244,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout chars (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -260,7 +260,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout chars (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -276,7 +276,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stdout binary (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -292,7 +292,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stdout string (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -309,7 +309,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stdout string (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -326,7 +326,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr chars (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -342,7 +342,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr chars (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -358,7 +358,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "redirect stderr binary (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -374,7 +374,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stderr string (Unix)" taggedAs OsUnix in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | @@ -390,7 +390,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { "return stderr string (Windows)" taggedAs OsWindows in { val code = - """from Standard.Builtins import all + """import Standard.Base.System |import Standard.Base.Data.Array |from Standard.Base.Data.Boolean import all | diff --git a/test/Benchmarks/src/Main.enso b/test/Benchmarks/src/Main.enso index 1503b970983e..5c0362d79254 100644 --- a/test/Benchmarks/src/Main.enso +++ b/test/Benchmarks/src/Main.enso @@ -1,6 +1,8 @@ from Standard.Base import all import Standard.Test.Bench +import Standard.Base.Runtime.Debug +import Standard.Base.Runtime.State polyglot java import java.lang.Long diff --git a/test/Tests/src/Data/List_Spec.enso b/test/Tests/src/Data/List_Spec.enso index 82bbf9167986..d6b6698992c2 100644 --- a/test/Tests/src/Data/List_Spec.enso +++ b/test/Tests/src/Data/List_Spec.enso @@ -1,6 +1,7 @@ from Standard.Base import all import Standard.Base.Data.List +import Standard.Base.Runtime.State import Standard.Test diff --git a/test/Tests/src/Resource/Bracket_Spec.enso b/test/Tests/src/Resource/Bracket_Spec.enso index eba1563ab31c..ef97620037c0 100644 --- a/test/Tests/src/Resource/Bracket_Spec.enso +++ b/test/Tests/src/Resource/Bracket_Spec.enso @@ -1,5 +1,6 @@ from Standard.Base import all import Standard.Test +from Standard.Base.Runtime.Resource import all spec = Test.group "Resource.bracket" <| Test.specify "should call the destructor even if the action fails" <| diff --git a/test/Tests/src/Semantic/Runtime_Spec.enso b/test/Tests/src/Semantic/Runtime_Spec.enso index fa5f7064d588..d42b8e12ec88 100644 --- a/test/Tests/src/Semantic/Runtime_Spec.enso +++ b/test/Tests/src/Semantic/Runtime_Spec.enso @@ -1,5 +1,4 @@ -from Standard.Base import all - +import Standard.Base.Runtime import Standard.Test spec = Test.group "Inlining Helpers" <| diff --git a/test/Tests/src/System/Process_Spec.enso b/test/Tests/src/System/Process_Spec.enso index 5a2a5bca2d7f..f85dba2e7c24 100644 --- a/test/Tests/src/System/Process_Spec.enso +++ b/test/Tests/src/System/Process_Spec.enso @@ -88,3 +88,5 @@ spec = Test.group "Process" <| result.stderr . should_equal "" Platform.Unknown -> Test.fail "Unsupported platform." + +main = Test.Suite.run_main here.spec From e4037b492ecadeca436eca9208cef53d7e96cbc6 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 22 Apr 2022 14:49:04 +0200 Subject: [PATCH 42/73] Move Prim_Warning to stdlib --- .../Standard/Base/0.0.0-dev/src/Warning.enso | 34 +++++++++++++++++++ .../interpreter/runtime/builtin/Builtins.java | 1 - .../interpreter/runtime/builtin/Warning.java | 22 ------------ .../runtime/src/main/resources/Builtins.enso | 32 ----------------- 4 files changed, 34 insertions(+), 55 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Warning.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso index e5f9c4122480..ea1a51ea0c08 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso @@ -186,3 +186,37 @@ merge_matched_warnings value matcher merger = new_warnings = merger (result.second.map .value) new_warnings.fold result.first acc-> warning-> Warning.attach warning acc + +## PRIVATE + +type Prim_Warning + + type Prim_Warning + + ## PRIVATE + attach : Any -> Any -> Any -> Any + attach value warning origin = @Builtin_Method "Prim_Warning.attach" + + ## PRIVATE + create : Any -> Any -> Prim_Warning + create payload origin = @Builtin_Method "Prim_Warning.create" + + ## PRIVATE + get_all : Any -> Array Prim_Warning + get_all value = @Builtin_Method "Prim_Warning.get_all" + + ## PRIVATE + set : Any -> Array Prim_Warning -> Any + set value warnings = @Builtin_Method "Prim_Warning.set" + + ## PRIVATE + get_origin : Prim_Warning -> Any + get_origin warn = @Builtin_Method "Prim_Warning.get_origin" + + ## PRIVATE + get_value : Prim_Warning -> Any + get_value warn = @Builtin_Method "Prim_Warning.get_value" + + ## PRIVATE + get_reassignments : Prim_Warning -> Any + get_reassignments warn = @Builtin_Method "Prim_Warning.get_reassignments" diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 361d52355ff4..9cf309d0e6a4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -124,7 +124,6 @@ public Builtins(Context context) { system = new System(this); // TODO: Builtins that are not yet moved to stdlib - Warning.initWarningMethods(language, scope); number = new Number(language, scope); special = new Special(language); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Warning.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Warning.java deleted file mode 100644 index a3a4ec1ef757..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Warning.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.warning.*; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -public class Warning { - public static void initWarningMethods(Language language, ModuleScope scope) { - var warning = new AtomConstructor("Prim_Warning", scope).initializeFields(); - - scope.registerConstructor(warning); - scope.registerMethod(warning, "get_all", GetWarningsMethodGen.makeFunction(language)); - scope.registerMethod(warning, "create", CreateWarningMethodGen.makeFunction(language)); - scope.registerMethod(warning, "attach", AttachWarningMethodGen.makeFunction(language)); - scope.registerMethod(warning, "get_value", GetValueMethodGen.makeFunction(language)); - scope.registerMethod(warning, "get_origin", GetOriginMethodGen.makeFunction(language)); - scope.registerMethod( - warning, "get_reassignments", GetReassignmentsMethodGen.makeFunction(language)); - scope.registerMethod(warning, "set", SetWarningsMethodGen.makeFunction(language)); - } -} diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 567e590b929d..37ddfb3ed224 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -4,38 +4,6 @@ # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. -@Builtin_Type -type Prim_Warning - type Prim_Warning - - ## PRIVATE - attach : Any -> Any -> Any -> Any - attach value warning origin = @Builtin_Method "Prim_Warning.attach" - - ## PRIVATE - create : Any -> Any -> Prim_Warning - create payload origin = @Builtin_Method "Prim_Warning.create" - - ## PRIVATE - get_all : Any -> Array Prim_Warning - get_all value = @Builtin_Method "Prim_Warning.get_all" - - ## PRIVATE - set : Any -> Array Prim_Warning -> Any - set value warnings = @Builtin_Method "Prim_Warning.set" - - ## PRIVATE - get_origin : Prim_Warning -> Any - get_origin warn = @Builtin_Method "Prim_Warning.get_origin" - - ## PRIVATE - get_value : Prim_Warning -> Any - get_value warn = @Builtin_Method "Prim_Warning.get_value" - - ## PRIVATE - get_reassignments : Prim_Warning -> Any - get_reassignments warn = @Builtin_Method "Prim_Warning.get_reassignments" - ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or From 1a586d9ab4537a458729c087f46884a6dd94dc05 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 09:26:45 +0200 Subject: [PATCH 43/73] Builtins is dead, long live builtins The last in the bunch of official builtins moved to stdlib. Unfortunately couldn't move to a better hierarchy in stdlib such as - Data/Number.enso - Data/Number/Integer.enso - Data/Number/Decimal.enso because symbol resolution when pattern matching on Number always picks the Module symbol not the type and changing everything to `case Number.Number` is super ugly. Had similar problems with other modules but this one would be nasty to use that way. Discovered some typos in original builtins (probably due to c&p) which got only revealed after methods were no longer being hardcoded when registering them with constructors. Also, some builtin methods nodes appear more than once under different names, hence the introduction of aliases parameter. Lastly, Number and Integer does not conform to the rest of the schema since their definitions in Builtins.enso were only for documentation purposes, or at least it appears so. Hence the tiny exception when translating IR to Truffle to ignore their builtin methods. --- .../0.0.0-dev/src/Data/Json/Internal.enso | 4 +- .../Base/0.0.0-dev/src/Data/List.enso | 2 +- .../0.0.0-dev/src/Data/Number/Extensions.enso | 324 ------ .../0.0.0-dev/src/Data/Number/Internal.enso | 997 ++++++++++++++++++ .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 10 +- .../fixtures/semantic/AtomFixtures.scala | 2 +- .../fixtures/semantic/CallableFixtures.scala | 2 +- .../fixtures/semantic/RecursionFixtures.scala | 4 +- .../expression/builtin/number/BigInteger.java | 8 + .../expression/builtin/number/Decimal.java | 7 + .../expression/builtin/number/Integer.java | 8 + .../expression/builtin/number/Number.java | 8 + .../builtin/number/SmallInteger.java | 8 + .../number/bigInteger/BitShiftNode.java | 2 +- .../builtin/number/smallInteger/AbsNode.java | 2 +- .../number/smallInteger/BitShiftNode.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 2 +- .../interpreter/runtime/builtin/Number.java | 406 +------ .../interpreter/runtime/type/Constants.java | 10 +- .../runtime/src/main/resources/Builtins.enso | 663 ------------ .../enso/compiler/codegen/IrToTruffle.scala | 32 +- .../test/instrument/ReplTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 82 +- .../RuntimeSuggestionUpdatesTest.scala | 4 +- .../RuntimeVisualisationsTest.scala | 58 +- .../test/semantic/InteropTest.scala | 2 +- .../semantic/LambdaShorthandArgsTest.scala | 8 +- .../test/semantic/LambdaTest.scala | 2 +- .../interpreter/test/semantic/StateTest.scala | 10 +- .../enso/interpreter/dsl/BuiltinMethod.java | 3 + .../enso/interpreter/dsl/MethodProcessor.java | 6 + .../dsl/model/MethodDefinition.java | 16 + test/Tests/src/Data/Numbers_Spec.enso | 2 +- test/Tests/src/Semantic/Meta_Spec.enso | 4 +- 34 files changed, 1236 insertions(+), 1466 deletions(-) delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso index b206042c9817..2c5357ce3470 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso @@ -1,5 +1,7 @@ from Standard.Base import all hiding Number, Boolean, Array +import Standard.Base.Data.Number.Internal as Base_Number + from Standard.Base.Data.Json import all polyglot java import org.enso.base.json.Parser @@ -291,7 +293,7 @@ into_helper fmt json = case fmt of Base.Boolean -> case json of Boolean v -> v _ -> Panic.throw (Type_Mismatch_Error json fmt) - Base.Number -> case json of + Base_Number.Number -> case json of Number v -> v _ -> Panic.throw (Type_Mismatch_Error json fmt) Base.Text -> case json of diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 09d23567e92e..ba97fb041189 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,4 +1,4 @@ -from Standard.Builtins import Number,Integer +from Standard.Base.Data.Number.Internal import all from Standard.Base.Error.Common import Error from Standard.Base.Data.Boolean import True, False import Standard.Base.Nothing diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso deleted file mode 100644 index dc3280f2d26a..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso +++ /dev/null @@ -1,324 +0,0 @@ -from Standard.Base import all hiding Parse_Error - -polyglot java import java.lang.Long -polyglot java import java.lang.Double -polyglot java import java.lang.Math -polyglot java import java.lang.String -polyglot java import java.lang.NumberFormatException - -## ALIAS Inverse Sine - - Computes the inverse of the sine function - - Selects a value in the -pi/2 through pi/2 range. - - > Example - Calculate the inverse sine of 1. - - 1.asin -Number.asin : Decimal -Number.asin = Math.asin this.to_decimal - -## ALIAS Inverse Cosine - - Computes the inverse of the cosine function. - - Selects a value in the -pi/2 through pi/2 range. - - > Example - Calculate the inverse cosine of 1. - - 1.acos -Number.acos : Decimal -Number.acos = Math.acos this.to_decimal - -## ALIAS Inverse Tangent - - Computes the inverse of the tangent function. - - Selects a value in the -pi/2 through pi/2 range. - - > Example - Calculate the inverse tangent of 1. - - 1.atan -Number.atan : Decimal -Number.atan = Math.atan this.to_decimal - -## Computes the argument (angle) in the conversion from cartesian - to polar coordinates, taking `this` as the x coordinate. - - Arguments: - - y: The y coordinate. - - The returned angle is in the -pi through pi range. - - > Example - Convert the coordinates 1 and 2 to polar form. - - 1.atan_2 2 -Number.atan_2 : Number -> Decimal -Number.atan_2 y = Math.atan2 this.to_decimal y.to_decimal - -## ALIAS Sine - - Computes the sine function. - - > Example - Calculate the sine of 2. - - 2.sin -Number.sin : Decimal -Number.sin = Math.sin this.to_decimal - -## ALIAS Cosine - - Computes the cosine function. - - > Example - Calculate the cosine of 2. - - 2.cos -Number.cos : Decimal -Number.cos = Math.cos this.to_decimal - -## ALIAS Tangent - - Computes the tangent function. - - > Example - Calculate the tangent of 2. - - 2.tan -Number.tan : Decimal -Number.tan = Math.tan this.to_decimal - -## Computes the hyperbolic sine function. - - > Example - Calculate the hyperbolic sine of 1. - - 1.sinh -Number.sinh : Decimal -Number.sinh = Math.sinh this.to_decimal - -## Computes the hyperbolic cosine function. - - > Example - Calcualte the hyperbolic cosine of 1. - - 1.cosh -Number.cosh : Decimal -Number.cosh = Math.cosh this.to_decimal - -## Computes the hyperbolic tangent function. - - > Example - Calculate the hyperbolic tangent of 1. - - 1.tanh -Number.tanh : Decimal -Number.tanh = Math.tanh this.to_decimal - -## ALIAS Exponential - - Computes the exponential function, raising Euler's number `r` to the power of - `this`. - - > Example - Calculate e to the 4th power. - - 4.exp -Number.exp : Decimal -Number.exp = Math.exp this.to_decimal - -## ALIAS Natural Logarithm - - Computes the natural logarithm function. - - > Example - Calculate the natural logarithm of 2. - - 2.ln -Number.ln : Decimal -Number.ln = Math.log this.to_decimal - -## ALIAS Square Root - - Computes the square root of `this`. - - > Example - Calculate the square root of 8. - - 8.sqrt -Number.sqrt : Decimal -Number.sqrt = Math.sqrt this.to_decimal - -## ALIAS Logarithm - - Computes the `base`-log of `this`. - - Arguments: - - base: The base for the logarithm. - - > Example - Calculate log 2 of 4. - - 4.log 2 -Number.log : Number -> Decimal -Number.log base = this.ln / base.ln - -## UNSTABLE This API is not user-friendly and will be improved in the future. - - Converts a numeric value to a string, using the Java string formatting - syntax. - - Arguments: - - fmt: The java-style formatting specifier. - - > Example - Convert the value 5 to a string. - - 5.format "%x" -Number.format : Text -> Text -Number.format fmt = String.format fmt this - -## ALIAS Range - - Creates a new right-exclusive range of integers from `this` to `n`. - - Arguments: - - n: The end of the range. - - > Example - Create a range containing the numbers 0, 1, 2, 3, 4. - - 0.up_to 5 -Integer.up_to : Integer -> Range -Integer.up_to n = Range this n - -## Checks equality of numbers, using an `epsilon` value. - - Arguments: - - that: The number to check equality against. - - epsilon: The value by which `this` and `that` can be separated by before - counting as not equal. - - > Example - Check if 1 is equal to 1.0000001 within 0.001. - - 1.equals 1.0000001 epsilon=0.001 -Number.equals : Number -> Number -> Boolean -Number.equals that epsilon=0.0 = - (this == that) || ((this - that).abs <= epsilon) - -## Returns the smaller value of `this` and `that`. - - Arguments: - - that: The number to compare `this` against. - - ? Math.min or Number.min - While we provide the min method on `Number`, we find it more intuitive to - write `Math.min a b` rather than `a.min b`. To that end, we recommend using - the first style. - - > Example - Find the minimum of 2 and 5. - - 2.min 5 -Number.min : Number -> Number -Number.min that = if this < that then this else that - -## Returns the larger value of `this` and `that`. - - Arguments: - - that: The number to compare `this` against. - - ? Math.max or Number.max - While we provide the max method on `Number`, we find it more intuitive to - write `Math.max a b` rather than `a.max b`. To that end, we recommend using - the first style. - - > Example - Find the maximum of 2 and 5. - - 2.max 5 -Number.max : Number -> Number -Number.max that = if this > that then this else that - -## Number to JSON conversion. - - > Example - Convert the number 8 to JSON. - - 8.to_json -Number.to_json : Json.Number -Number.to_json = Json.Number this - -## ALIAS From Text - - Parses a textual representation of an integer into an integer number, returning - a `Parse_Error` if the text does not represent a valid integer. - - Arguments: - - text: The text to parse into a integer. - - radix: The number base to use for parsing (defaults to 10). - - > Example - Parse the text "20220216" into an integer number. - - Integer.parse "20220216" -Integer.parse : Text -> Text -> Integer ! Parse_Error -Integer.parse text (radix=10) = - Panic.catch NumberFormatException (Long.parseLong text radix) _-> - Error.throw (Parse_Error text) - -## ALIAS From Text - - Parses a textual representation of a decimal into a decimal number, returning - a `Parse_Error` if the text does not represent a valid decimal. - - Arguments: - - text: The text to parse into a decimal. - - > Example - Parse the text "7.6" into a decimal number. - - Decimal.parse "7.6" -Decimal.parse : Text -> Decimal ! Parse_Error -Decimal.parse text = - Panic.catch NumberFormatException (Double.parseDouble text) _-> - Error.throw (Parse_Error text) - -## UNSTABLE - - A syntax error when parsing a double. -type Parse_Error text - -## UNSTABLE - - Pretty print the syntax error. -Parse_Error.to_display_text : Text -Parse_Error.to_display_text = - "Could not parse " + this.text.to_text + " as a double." - -## A constant holding the floating-point positive infinity. -Number.positive_infinity : Decimal -Number.positive_infinity = Double.POSITIVE_INFINITY - -## A constant holding the floating-point negative infinity. -Number.negative_infinity : Decimal -Number.negative_infinity = Double.NEGATIVE_INFINITY - -## A constant holding the floating-point Not-a-Number value. -Number.nan : Decimal -Number.nan = Double.NaN - -## Checks if the given number is the floating-point Not-a-Number value. - - This is needed, because the NaN value will return `False` even when being - compared with itself, so `x == Number.nan` would not work. -Number.is_nan : Boolean -Number.is_nan = case this of - Decimal -> Double.isNaN this - _ -> False diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso new file mode 100644 index 000000000000..6b5804e42f99 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso @@ -0,0 +1,997 @@ +polyglot java import java.lang.Double +polyglot java import java.lang.Math +polyglot java import java.lang.String +polyglot java import java.lang.Long +polyglot java import java.lang.NumberFormatException + +import Standard.Base.Data.Json +from Standard.Base.Data.Boolean import all +from Standard.Base.Data.Range import all +from Standard.Base.Error.Common import Panic,Error +## The root type of the Enso numeric hierarchy. + + If a Number is expected, then the program can provide either a Decimal or + an Integer in its place. +type Number + + ## The root type of the Enso numeric hierarchy. + + If a Number is expected, then the program can provide either a Decimal or + an Integer in its place. + @Builtin_Type + type Number + + ## ALIAS Add + + Adds two arbitrary numbers. + + Arguments: + - that: The number to add to this. + + Addition in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Adding 10 and 15. + + 10 + 15 + + : Number -> Number + + that = @Builtin_Method "Integer.+" + + ## ALIAS Subtract + + Subtract an arbitrary number from this. + + Arguments: + - that: The number to subtract from this. + + > Example + Subtract 5 from 2. + + 2 - 5 + - : Number -> Number + - that = @Builtin_Method "Integer.-" + + ## ALIAS Multiply + + Multiply two arbitrary numbers. + + Arguments: + - that: The number to multiply this by. + + Multiplication in Enso will undergo automatic conversions such that you + need not convert between Integer and Decimal manually. + + > Example + Multiplying 3 by 5. + + 3 * 5 + * : Number -> Number + * that = @Builtin_Method "Integer.*" + + ## ALIAS Divide + + Divides an this by an arbitrary number. + + Arguments: + - that: The number to divide this by. + + Division in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Dividing 10 by 4 to get 2.5. + + 10 / 4 + / : Number -> Number + / that = @Builtin_Method "Integer./" + + ## ALIAS Power + + Compute the result of raising this to the power that. + + Arguments: + - that: The exponent. + + > Example + Computing 2 cubed. + + 2^3 + ^ : Number -> Number + ^ that = @Builtin_Method "Integer.^" + + ## ALIAS Inverse Sine + + Computes the inverse of the sine function + + Selects a value in the -pi/2 through pi/2 range. + + > Example + Calculate the inverse sine of 1. + + 1.asin + asin : Decimal + asin = Math.asin this.to_decimal + + ## ALIAS Inverse Cosine + + Computes the inverse of the cosine function. + + Selects a value in the -pi/2 through pi/2 range. + + > Example + Calculate the inverse cosine of 1. + + 1.acos + acos : Decimal + acos = Math.acos this.to_decimal + + ## ALIAS Inverse Tangent + + Computes the inverse of the tangent function. + + Selects a value in the -pi/2 through pi/2 range. + + > Example + Calculate the inverse tangent of 1. + + 1.atan + atan : Decimal + atan = Math.atan this.to_decimal + + ## Computes the argument (angle) in the conversion from cartesian + to polar coordinates, taking `this` as the x coordinate. + + Arguments: + - y: The y coordinate. + + The returned angle is in the -pi through pi range. + + > Example + Convert the coordinates 1 and 2 to polar form. + + 1.atan_2 2 + atan_2 : Number -> Decimal + atan_2 y = Math.atan2 this.to_decimal y.to_decimal + + ## ALIAS Sine + + Computes the sine function. + + > Example + Calculate the sine of 2. + + 2.sin + sin : Decimal + sin = Math.sin this.to_decimal + + ## ALIAS Cosine + + Computes the cosine function. + + > Example + Calculate the cosine of 2. + + 2.cos + cos : Decimal + cos = Math.cos this.to_decimal + + ## ALIAS Tangent + + Computes the tangent function. + + > Example + Calculate the tangent of 2. + + 2.tan + tan : Decimal + tan = Math.tan this.to_decimal + + ## Computes the hyperbolic sine function. + + > Example + Calculate the hyperbolic sine of 1. + + 1.sinh + sinh : Decimal + sinh = Math.sinh this.to_decimal + + ## Computes the hyperbolic cosine function. + + > Example + Calcualte the hyperbolic cosine of 1. + + 1.cosh + cosh : Decimal + cosh = Math.cosh this.to_decimal + + ## Computes the hyperbolic tangent function. + + > Example + Calculate the hyperbolic tangent of 1. + + 1.tanh + tanh : Decimal + tanh = Math.tanh this.to_decimal + + ## ALIAS Exponential + + Computes the exponential function, raising Euler's number `r` to the power of + `this`. + + > Example + Calculate e to the 4th power. + + 4.exp + exp : Decimal + exp = Math.exp this.to_decimal + + ## ALIAS Natural Logarithm + + Computes the natural logarithm function. + + > Example + Calculate the natural logarithm of 2. + + 2.ln + ln : Decimal + ln = Math.log this.to_decimal + + ## ALIAS Square Root + + Computes the square root of `this`. + + > Example + Calculate the square root of 8. + + 8.sqrt + sqrt : Decimal + sqrt = Math.sqrt this.to_decimal + + ## ALIAS Logarithm + + Computes the `base`-log of `this`. + + Arguments: + - base: The base for the logarithm. + + > Example + Calculate log 2 of 4. + + 4.log 2 + log : Number -> Decimal + log base = this.ln / base.ln + + ## UNSTABLE This API is not user-friendly and will be improved in the future. + + Converts a numeric value to a string, using the Java string formatting + syntax. + + Arguments: + - fmt: The java-style formatting specifier. + + > Example + Convert the value 5 to a string. + + 5.format "%x" + format : Text -> Text + format fmt = String.format fmt this + + ## Checks equality of numbers, using an `epsilon` value. + + Arguments: + - that: The number to check equality against. + - epsilon: The value by which `this` and `that` can be separated by before + counting as not equal. + + > Example + Check if 1 is equal to 1.0000001 within 0.001. + + 1.equals 1.0000001 epsilon=0.001 + equals : Number -> Number -> Boolean + equals that epsilon=0.0 = + (this == that) || ((this - that).abs <= epsilon) + + ## Returns the smaller value of `this` and `that`. + + Arguments: + - that: The number to compare `this` against. + + ? Math.min or Number.min + While we provide the min method on `Number`, we find it more intuitive to + write `Math.min a b` rather than `a.min b`. To that end, we recommend using + the first style. + + > Example + Find the minimum of 2 and 5. + + 2.min 5 + min : Number -> Number + min that = if this < that then this else that + + ## Returns the larger value of `this` and `that`. + + Arguments: + - that: The number to compare `this` against. + + ? Math.max or Number.max + While we provide the max method on `Number`, we find it more intuitive to + write `Math.max a b` rather than `a.max b`. To that end, we recommend using + the first style. + + > Example + Find the maximum of 2 and 5. + + 2.max 5 + max : Number -> Number + max that = if this > that then this else that + + ## Number to JSON conversion. + + > Example + Convert the number 8 to JSON. + + 8.to_json + to_json : Json.Number + to_json = Json.Number this + + ## A constant holding the floating-point positive infinity. + positive_infinity : Decimal + positive_infinity = Double.POSITIVE_INFINITY + + ## A constant holding the floating-point negative infinity. + negative_infinity : Decimal + negative_infinity = Double.NEGATIVE_INFINITY + + ## A constant holding the floating-point Not-a-Number value. + nan : Decimal + nan = Double.NaN + + ## Checks if the given number is the floating-point Not-a-Number value. + + This is needed, because the NaN value will return `False` even when being + compared with itself, so `x == Number.nan` would not work. + is_nan : Boolean + is_nan = case this of + Decimal -> Double.isNaN this + _ -> False + + +################### +## Decimal +################### +## Decimal numbers. + +type Decimal + + ## Decimal is the type of decimal numbers in Enso. + + ? Representation + Enso's decimal numbers are represented as IEEE754 double-precision + floating point numbers. + @Builtin_Type + type Decimal + + ## Adds a deceimal and an arbitrary number. + + Arguments: + - that: The number to add to this. + + Addition in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Adding 10.1 and 15. + + 10.1 + 15 + + : Number -> Number + + that = @Builtin_Method "Decimal.+" + + ## Subtract an arbitrary number from this. + + Arguments: + - that: The number to subtract from this. + + > Example + Subtract 5 from 2.78. + + 2.78 - 5 + - : Number -> Number + - that = @Builtin_Method "Decimal.-" + + ## Multiply a decimal by an arbitrary number. + + Arguments: + - that: The number to multiply this by. + + Multiplication in Enso will undergo automatic conversions such that you + need not convert between Integer and Decimal manually. + + > Example + Multiplying 3 by 5.27. + + 5.27 * 3 + * : Number -> Number + * that = @Builtin_Method "Decimal.*" + + ## Divides a decimal by an arbitrary number. + + Arguments: + - that: The number to divide this by. + + Division in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Dividing 10 by 4.5. + + 10 / 4.5 + / : Number -> Number + / that = @Builtin_Method "Decimal./" + + ## Compute the result of raising this to the power that. + + Arguments: + - that: The exponent. + + > Example + Computing 2.2 cubed. + + 2.2^3 + ^ : Number -> Number + ^ that = @Builtin_Method "Decimal.^" + + ## Compares this and that for equality. + + Arguments: + - that: The number to compare this against. + + > Example + Comparing 7 and 2.1 for equality. + + 7 == 2.1 + == : Number -> Boolean + == that = @Builtin_Method "Decimal.==" + + ## Checks if this is greater than that. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is greater than 7.3. + + 10 > 7.3 + > : Number -> Boolean + > that = @Builtin_Method "Decimal.>" + + ## Checks if this is greater than or equal to thatthat. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is greater than or equal to 7.3. + + 10 >= 7.3 + >= : Number -> Boolean + >= that = @Builtin_Method "Decimal.>=" + + ## Checks if this is less than that. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is less than 7.3. + + 10 < 7.3 + < : Number -> Boolean + < that = @Builtin_Method "Decimal.<" + + ## Checks if this is less than or equal to thatthat. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10.4 is less than or equal to 7. + + 10.4 <= 7 + <= : Number -> Boolean + <= that = @Builtin_Method "Decimal.<=" + + ## Computes the absolute value of this. + + The absolute value of a positive number is itself, while the absolute + value of a negative number is that number multiplied by -1. + + > Example + Computing the absolute value of -10.63. + + -10.63.abs + abs : Decimal + abs = @Builtin_Method "Decimal.abs" + + ## Computes the nearest integer above this number. + + This method provides a means of converting a Decimal to an Integer. + + > Example + Computing the ceiling of 4.736 (which is 5). + + 4.736.ceil + ceil : Integer + ceil = @Builtin_Method "Integer.ceil" + + ## Compares the two operands to determine the ordering of this with + respect to that. + + Arguments: + - that: The operand to order this with respect to. + + > Example + Computing the ordering of 1.732 and 4 (Less). + + 1.732.compare_to 4 + compare_to : Number -> Ordering + compare_to that = @Builtin_Method "Decimal.compare_to" + + ## Computes the nearest integer below this decimal. + + This method provides a means of converting a Decimal to an Integer. + + > Example + Computing the floor of 4.323 (which is 4). + + 4.323.floor + floor : Integer + floor = @Builtin_Method "Decimal.floor" + + ## Compute the negation of this. + + > Example + Negate 5.1 to get -5.1. + + 5.1.negate + negate : Decimal + negate = @Builtin_Method "Decimal.negate" + + ## Convert this to a decimal. + + This is a no-op on decimals, but is provided for completeness of the Enso + Number API. + + > Example + Convert 5.0 to a decimal to get 5.0. + + 5.0.to_decimal + to_decimal : Decimal + to_decimal = @Builtin_Method "Decimal.to_decimal" + + ## ALIAS From Text + + Parses a textual representation of a decimal into a decimal number, returning + a `Parse_Error` if the text does not represent a valid decimal. + + Arguments: + - text: The text to parse into a decimal. + + > Example + Parse the text "7.6" into a decimal number. + + Decimal.parse "7.6" + parse : Text -> Decimal ! Parse_Error + parse text = + Panic.catch NumberFormatException (Double.parseDouble text) _-> + Error.throw (Parse_Error text) + +################ +## Integer +################ +## Integral numbers. +type Integer + + ## Integer is the type of integral numbers in Enso. They are of unbounded + size and can grow as large as necessary. + + ? Representation + For certain operations (such as bitwise logic), the underlying + representation of the number matters. Enso Integers are represented as + signed 2's complement numbers. + + ? Performance + Integers that fit into 64 bits are represented in memory as 64 bits. + This means that operations on them achieve excellent performance. Once + the integer grows beyond being able to fit in 64 bits, performance will + degrade. + @Builtin_Type + type Integer + + ## Adds an integer and an arbitrary number. + + Arguments: + - that: The number to add to this. + + Addition in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Adding 10 and 15. + + 10 + 15 + + : Number -> Number + + that = @Builtin_Method "Integer.+" + + ## Subtract an arbitrary number from this. + + Arguments: + - that: The number to subtract from this. + + > Example + Subtract 5 from 2. + + 2 - 5 + - : Number -> Number + - that = @Builtin_Method "Integer.-" + + ## Multiply an integer by an arbitrary number. + + Arguments: + - that: The number to multiply this by. + + Multiplication in Enso will undergo automatic conversions such that you + need not convert between Integer and Decimal manually. + + > Example + Multiplying 3 by 5. + + 3 * 5 + * : Number -> Number + * that = @Builtin_Method "Integer.*" + + ## Divides an integer by an arbitrary number. + + Arguments: + - that: The number to divide this by. + + Division in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + > Example + Dividing 10 by 4 to get 2.5. + + 10 / 4 + / : Number -> Number + / that = @Builtin_Method "Integer./" + + ## Computes the remainder when dividing this by that. + + Arguments: + - that: The number to divide this by. + + Modulus in Enso will undergo automatic conversions such that you need + not convert between Integer and Decimal manually. + + Returns an error if the shift amount exceeds 2^32. + + > Example + Computing the remainder when dividing 10 by 3 (which is 1). + + 10 % 3 + % : Number -> Number ! Arithmetic_Error + % that = @Builtin_Method "Integer.%" + + ## Compute the result of raising this to the power that. + + Arguments: + - that: The exponent. + + > Example + Computing 2 cubed. + + 2^3 + ^ : Number -> Number + ^ that = @Builtin_Method "Integer.^" + + ## Compares this and that for equality. + + Arguments: + - that: The number to compare this against. + + > Example + Comparing 7 and 2 for equality. + + 7 == 2 + == : Number -> Boolean + == that = @Builtin_Method "Integer.==" + + ## Checks if this is greater than that. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is greater than 7. + + 10 > 7 + > : Number -> Boolean + > that = @Builtin_Method "Integer.>" + + ## Checks if this is greater than or equal to thatthat. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is greater than or equal to 7. + + 10 >= 7 + >= : Number -> Boolean + >= that = @Builtin_Method "Integer.>=" + + ## Checks if this is less than that. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is less than 7. + + 10 < 7 + < : Number -> Boolean + < that = @Builtin_Method "Integer.<" + + ## Checks if this is less than or equal to thatthat. + + Arguments: + - that: The number to compare this against. + + > Example + Checking if 10 is less than or equal to 7. + + 10 <= 7 + <= : Number -> Boolean + <= that = @Builtin_Method "Integer.<=" + + ## Computes the absolute value of this. + + The absolute value of a positive number is itself, while the absolute + value of a negative number is that number multiplied by -1. + + > Example + Computing the absolute value of -10. + + -10.abs + abs : Integer + abs = @Builtin_Method "Integer.abs" + + ## Computes the nearest integer above this integer. + + This is a no-op on integers but is provided for completeness of the Enso + number API. + + > Example + Computing the ceiling of 4. + + 4.ceil + ceil : Integer + ceil = @Builtin_Method "Integer.ceil" + + ## Compares the two operands to determine the ordering of this with + respect to that. + + Arguments: + - that: The operand to order this with respect to. + + > Example + Computing the ordering of 1 and 4 (Less). + + 1.compare_to 4 + compare_to : Number -> Ordering + compare_to that = @Builtin_Method "Integer.compare_to" + + ## Computes the integer division of this by that. + + Arguments: + - that: The number to divide this by. + + Integer division rounds down to the nearest integer. + + Returns an error if `that` is zero. + + > Example + Dividing 10 by 3 to get 3. + + 10.div 3 + div : Integer -> Number ! Arithmetic_Error + div that = @Builtin_Method "Integer.div" + + ## Computes the nearest integer below this integer. + + This is a no-op on integers but is provided for completeness of the Enso + number API. + + > Example + Computing the floor of 4. + + 4.floor + floor : Integer + floor = @Builtin_Method "Integer.floor" + + ## Compute the negation of this. + + > Example + Negate 5 to get -5. + + 5.negate + negate : Integer + negate = @Builtin_Method "Integer.negate" + + ## Convert this to a decimal. + + > Example + Convert 5 to a decimal to get 5.0. + + 5.to_decimal + to_decimal : Decimal + to_decimal = @Builtin_Method "Integer.to_decimal" + + ## Computes the bitwise and (conjunction) operation between this and + that. + + Arguments: + - that: The number to compute the bitwise conjunction with. + + Bitwise and computes the logical conjunction of the corresponding pairs + of bits in the operands. + + ? Example + Computing the bitwise conjunction of 2_01101101 and 2_11110000. + + 2_01101101.bit_and 2_11110000 + bit_and : Integer -> Integer + bit_and that = @Builtin_Method "Integer.bit_and" + + ## Computes the bitewise compliment of this. + + The bitwise compliment negates the value of each bit in the operand. + + ? Example + Bitwise negation of 2_0110. + + 2_0110.bit_not + bit_not : Integer + bit_not = @Builtin_Method "Integer.bit_not" + + ## Computes the bitwise or (disjunction) operation between this and + that. + + Arguments: + - that: The number to compute the bitwise disjunction with. + + Bitwise or computes the logical disjunction of the pairs of corresponding + bits in the operands. + + > Example + Computing the bitwise disjunction of 2_01101101 and 2_11110000. + + 2_01101101.bit_or 2_11110000 + bit_or : Integer -> Integer + bit_or that = @Builtin_Method "Integer.bit_or" + + ## Computes the bitwise exclusive or between this and that. + + Arguments: + - that: The number to compute the bitwise exclusive or with. + + Bitwise exclusive or computes the exclusive or of the pairs of + corresponding bits in the operands. + + > Example + Computing the bitwise exclusive or of 2_01101101 and 2_11110000. + + 2_01101101.bit_xor 2_11110000 + bit_xor : Integer -> Integer + bit_xor that = @Builtin_Method "Integer.bit_xor" + + ## Shifts the bits of this by the amount that. + + Arguments: + - that: The number of bits by which the shift should be performed. + Positive numbers perform a left shift, while negative numbers perform a + right shift. + + Leftwise bit shifts fill the new bits with zeroes, while rightwise bit + shifts perform sign extension. + + Returns an error if the shift amount exceeds 2^32. + + > Example + Shift the bits of the number 1 left by four bits. + + 1.bit_shift 4 + bit_shift : Integer -> Integer ! Arithmetic_Error + bit_shift that = @Builtin_Method "Integer.bit_shift" + + ## Performs a left-wise bit shift on the bits of this. + + Arguments: + - that: The number of bits by which the shift should be performed. + Positive numbers perform a left shift, while negative numbers perform a + right shift. + + Leftwise bit shifts fill the new bits with zeroes, while rightwise bit + shifts perform sign extension. + + Returns an error if the shift amount exceeds 2^32. + + > Example + Shift the bits of the number 1 left by four bits. + + 1.bit_shift_l 4 + bit_shift_l : Integer -> Integer ! Arithmetic_Error + bit_shift_l that = @Builtin_Method "Integer.bit_shift_l" + + ## Performs a right-wise bit shift on the bits of this. + + Arguments: + - that: The number of bits by which the shift should be performed. + Positive numbers perform a right shift, while negative numbers perform + a left shift. + + Leftwise bit shifts fill the new bits with zeroes, while rightwise bit + shifts perform sign extension. + + Returns an error if the shift amount exceeds 2^32. + + > Example + Shift the bits of the number 1 right by four bits. + + 1.bit_shift_r 4 + bit_shift_r : Integer -> Integer ! Arithmetic_Error + bit_shift_r that = @Builtin_Method "Integer.bpit_shift_r" + + ## ALIAS Range + + Creates a new right-exclusive range of integers from `this` to `n`. + + Arguments: + - n: The end of the range. + + > Example + Create a range containing the numbers 0, 1, 2, 3, 4. + + 0.up_to 5 + up_to : Integer -> Range + up_to n = Range.Range this n + + ## ALIAS From Text + + Parses a textual representation of an integer into an integer number, returning + a `Parse_Error` if the text does not represent a valid integer. + + Arguments: + - text: The text to parse into a integer. + - radix: The number base to use for parsing (defaults to 10). + + > Example + Parse the text "20220216" into an integer number. + + Integer.parse "20220216" + parse : Text -> Text -> Integer ! Parse_Error + parse text (radix=10) = + Panic.catch NumberFormatException (Long.parseLong text radix) _-> + Error.throw (Parse_Error text) + +## UNSTABLE + + A syntax error when parsing a double. +type Parse_Error text + +## UNSTABLE + + Pretty print the syntax error. +Parse_Error.to_display_text : Text +Parse_Error.to_display_text = + "Could not parse " + this.text.to_text + " as a double." diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 9c15cfaee6f9..9f03a723a927 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -8,7 +8,7 @@ import project.Data.Locale import project.Data.Map import project.Data.Maybe import project.Data.Noise -import project.Data.Number.Extensions +import project.Data.Number.Internal import project.Data.Ordering import project.Data.Ordering.Sort_Order import project.Data.Pair @@ -38,8 +38,6 @@ import project.System.File import project.Data.Text.Regex.Mode as Regex_Mode import project.Warning -from Standard.Builtins import Number, Integer - export project.Data.Interval export project.Data.Json export project.Data.Locale @@ -65,10 +63,10 @@ from project.Data.Array export Array from project.Data.Any export all from project.Data.Boolean export all from project.Data.List export Nil, Cons, List -from project.Data.Number.Extensions export all hiding Math, String, Double +from project.Data.Number.Internal export all hiding Math, String, Double, Parse_Error from project.Data.Noise export all hiding Noise from project.Data.Pair export Pair -from project.Data.Range export Range +from project.Data.Range export all ## TODO [RW] Once autoscoping is implemented or automatic imports for ADTs are fixed in the IDE, we should revisit if we want to export ADTs like `Case` by default. It may be unnecessary pollution of scope, but until the issues are @@ -87,5 +85,3 @@ from project.Nothing export all from project.Polyglot export all from project.Runtime.Extensions export all from project.Runtime.Resource export all - -from Standard.Builtins export all diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index a7fdb21a4bce..6b8d5b744774 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -7,7 +7,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val millionElementList = eval( s"""|from Standard.Base.Data.List import Cons,Nil - |from Standard.Base.Data.Number.Extensions import all + |from Standard.Base.Data.Number.Internal import all | |main = | res = (1.up_to $million).fold Nil (acc -> x -> Cons x acc) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala index 3e0aebbb9447..494b88f79833 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala @@ -7,7 +7,7 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOfromCallCode = """ - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import all | |type Foo | diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala index 74fc762ac422..74a034f51851 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala @@ -49,7 +49,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val oversaturatedRecursiveCall = getMain(oversaturatedRecursiveCallTCOCode) val sumStateTCOCode = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.Runtime.State | |stateSum = n -> @@ -76,7 +76,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val sumTCOWithEval = getMain(sumTCOWithEvalCode) val nestedThunkSumCode = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.Runtime.State |import Standard.Base.Nothing | diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java new file mode 100644 index 000000000000..a25c5ead023f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.number; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class BigInteger extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java new file mode 100644 index 000000000000..a24d43a939df --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.number; +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class Decimal extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java new file mode 100644 index 000000000000..a06b6f0c4f60 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.number; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class Integer extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java new file mode 100644 index 000000000000..a3acc2b12457 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.number; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class Number extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java new file mode 100644 index 000000000000..4177e205c02c --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java @@ -0,0 +1,8 @@ +package org.enso.interpreter.node.expression.builtin.number; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class SmallInteger extends Builtin { +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java index ca5102e1ba51..0bdf652c3d96 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java @@ -16,7 +16,7 @@ import org.enso.interpreter.runtime.number.EnsoBigInteger; @ImportStatic(BigIntegerOps.class) -@BuiltinMethod(type = "Big_Integer", name = "bit_shift", description = "Bitwise shift.") +@BuiltinMethod(type = "Big_Integer", name = "bit_shift", description = "Bitwise shift.", aliases = "bit_shift_l") public abstract class BitShiftNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); private final ConditionProfile fitsInIntProfileLeftShift = diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AbsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AbsNode.java index 31c4596e1032..61de0089ff22 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AbsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AbsNode.java @@ -6,7 +6,7 @@ import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; import org.enso.interpreter.node.expression.builtin.number.utils.ToEnsoNumberNode; -@BuiltinMethod(type = "Small_Integer", name = "negate", description = "Negation for numbers.") +@BuiltinMethod(type = "Small_Integer", name = "abs", description = "Negation for numbers.") public abstract class AbsNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java index f361f0354c8c..a354f94ba88f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java @@ -16,7 +16,7 @@ import org.enso.interpreter.runtime.number.EnsoBigInteger; @ImportStatic(BigIntegerOps.class) -@BuiltinMethod(type = "Small_Integer", name = "bit_shift", description = "Bitwise shift.") +@BuiltinMethod(type = "Small_Integer", name = "bit_shift", description = "Bitwise shift.", aliases = "bit_shift_l") public abstract class BitShiftNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); private final ConditionProfile canShiftLeftInLongProfile = diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 9cf309d0e6a4..9cb93803b4ed 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -124,7 +124,7 @@ public Builtins(Context context) { system = new System(this); // TODO: Builtins that are not yet moved to stdlib - number = new Number(language, scope); + number = new Number(this);//language, scope); special = new Special(language); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java index c63a4bf0757c..8aa12582354d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java @@ -1,16 +1,33 @@ package org.enso.interpreter.runtime.builtin; +import com.oracle.truffle.api.CompilerDirectives; import org.enso.interpreter.Language; +import org.enso.interpreter.node.expression.builtin.number.BigInteger; +import org.enso.interpreter.node.expression.builtin.number.Decimal; +import org.enso.interpreter.node.expression.builtin.number.Integer; +import org.enso.interpreter.node.expression.builtin.number.SmallInteger; +import org.enso.interpreter.node.expression.builtin.ordering.Less; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; /** A container for all number-related builtins. */ public class Number { - private final AtomConstructor smallInteger; - private final AtomConstructor bigInteger; - private final AtomConstructor integer; - private final AtomConstructor number; - private final AtomConstructor decimal; + @CompilerDirectives.CompilationFinal + private AtomConstructor smallInteger; + + @CompilerDirectives.CompilationFinal + private AtomConstructor bigInteger; + + @CompilerDirectives.CompilationFinal + private AtomConstructor integer; + + @CompilerDirectives.CompilationFinal + private AtomConstructor number; + + @CompilerDirectives.CompilationFinal + private AtomConstructor decimal; + + private final Builtins builtins; /** * Creates and registers number builtins. @@ -18,387 +35,52 @@ public class Number { * @param language the current language instance. * @param scope the builtins scope. */ - public Number(Language language, ModuleScope scope) { - number = new AtomConstructor("Number", scope).initializeFields(); - smallInteger = new AtomConstructor("Small_Integer", scope).initializeFields(); - integer = new AtomConstructor("Integer", scope).initializeFields(); - bigInteger = new AtomConstructor("Big_Integer", scope).initializeFields(); - decimal = new AtomConstructor("Decimal", scope).initializeFields(); - - registerInt64Methods(language, scope); - registerBigIntegerMethods(language, scope); - registerDecimalMethods(language, scope); - - scope.registerConstructor(number); - scope.registerConstructor(smallInteger); - scope.registerConstructor(integer); - scope.registerConstructor(bigInteger); - scope.registerConstructor(decimal); - } - - private void registerInt64Methods(Language language, ModuleScope scope) { - scope.registerMethod( - smallInteger, - "+", - org.enso.interpreter.node.expression.builtin.number.smallInteger.AddMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "-", - org.enso.interpreter.node.expression.builtin.number.smallInteger.SubtractMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "*", - org.enso.interpreter.node.expression.builtin.number.smallInteger.MultiplyMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "^", - org.enso.interpreter.node.expression.builtin.number.smallInteger.PowMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "/", - org.enso.interpreter.node.expression.builtin.number.smallInteger.DivideMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "div", - org.enso.interpreter.node.expression.builtin.number.smallInteger.DivMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "%", - org.enso.interpreter.node.expression.builtin.number.smallInteger.ModMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "negate", - org.enso.interpreter.node.expression.builtin.number.smallInteger.NegateMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "abs", - org.enso.interpreter.node.expression.builtin.number.smallInteger.AbsMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "==", - org.enso.interpreter.node.expression.builtin.number.smallInteger.EqualsMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - ">", - org.enso.interpreter.node.expression.builtin.number.smallInteger.GreaterMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - ">=", - org.enso.interpreter.node.expression.builtin.number.smallInteger.GreaterOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "<", - org.enso.interpreter.node.expression.builtin.number.smallInteger.LessMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "<=", - org.enso.interpreter.node.expression.builtin.number.smallInteger.LessOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "to_decimal", - org.enso.interpreter.node.expression.builtin.number.smallInteger.ToDecimalMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "floor", - org.enso.interpreter.node.expression.builtin.number.smallInteger.FloorMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "ceil", - org.enso.interpreter.node.expression.builtin.number.smallInteger.CeilMethodGen.makeFunction( - language)); - scope.registerMethod( - smallInteger, - "bit_and", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitAndMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_or", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitOrMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_xor", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitXorMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_not", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitNotMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_shift", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitShiftMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_shift_l", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitShiftMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "bit_shift_r", - org.enso.interpreter.node.expression.builtin.number.smallInteger.BitShiftRightMethodGen - .makeFunction(language)); - scope.registerMethod( - smallInteger, - "compare_to", - org.enso.interpreter.node.expression.builtin.number.smallInteger.CompareToMethodGen - .makeFunction(language)); - } - - private void registerBigIntegerMethods(Language language, ModuleScope scope) { - - scope.registerMethod( - bigInteger, - "+", - org.enso.interpreter.node.expression.builtin.number.bigInteger.AddMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "-", - org.enso.interpreter.node.expression.builtin.number.bigInteger.SubtractMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "*", - org.enso.interpreter.node.expression.builtin.number.bigInteger.MultiplyMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "^", - org.enso.interpreter.node.expression.builtin.number.bigInteger.PowMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "/", - org.enso.interpreter.node.expression.builtin.number.bigInteger.DivideMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "div", - org.enso.interpreter.node.expression.builtin.number.bigInteger.DivMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "%", - org.enso.interpreter.node.expression.builtin.number.bigInteger.ModMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "negate", - org.enso.interpreter.node.expression.builtin.number.bigInteger.NegateMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "abs", - org.enso.interpreter.node.expression.builtin.number.bigInteger.AbsMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "==", - org.enso.interpreter.node.expression.builtin.number.bigInteger.EqualsMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - ">", - org.enso.interpreter.node.expression.builtin.number.bigInteger.GreaterMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - ">=", - org.enso.interpreter.node.expression.builtin.number.bigInteger.GreaterOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "<", - org.enso.interpreter.node.expression.builtin.number.bigInteger.LessMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "<=", - org.enso.interpreter.node.expression.builtin.number.bigInteger.LessOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "to_decimal", - org.enso.interpreter.node.expression.builtin.number.bigInteger.ToDecimalMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "floor", - org.enso.interpreter.node.expression.builtin.number.bigInteger.FloorMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "ceil", - org.enso.interpreter.node.expression.builtin.number.bigInteger.CeilMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "bit_and", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitAndMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "bit_or", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitOrMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "bit_xor", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitXorMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "bit_not", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitNotMethodGen.makeFunction( - language)); - scope.registerMethod( - bigInteger, - "bit_shift", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitShiftMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "bit_shift_l", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitShiftMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "bit_shift_r", - org.enso.interpreter.node.expression.builtin.number.bigInteger.BitShiftRightMethodGen - .makeFunction(language)); - scope.registerMethod( - bigInteger, - "compare_to", - org.enso.interpreter.node.expression.builtin.number.bigInteger.CompareToMethodGen - .makeFunction(language)); - } - - private void registerDecimalMethods(Language language, ModuleScope scope) { - - scope.registerMethod( - decimal, - "+", - org.enso.interpreter.node.expression.builtin.number.decimal.AddMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "-", - org.enso.interpreter.node.expression.builtin.number.decimal.SubtractMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "*", - org.enso.interpreter.node.expression.builtin.number.decimal.MultiplyMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "^", - org.enso.interpreter.node.expression.builtin.number.decimal.PowMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "/", - org.enso.interpreter.node.expression.builtin.number.decimal.DivideMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "negate", - org.enso.interpreter.node.expression.builtin.number.decimal.NegateMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "abs", - org.enso.interpreter.node.expression.builtin.number.decimal.AbsMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "==", - org.enso.interpreter.node.expression.builtin.number.decimal.EqualsMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - ">", - org.enso.interpreter.node.expression.builtin.number.decimal.GreaterMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - ">=", - org.enso.interpreter.node.expression.builtin.number.decimal.GreaterOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - decimal, - "<", - org.enso.interpreter.node.expression.builtin.number.decimal.LessMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "<=", - org.enso.interpreter.node.expression.builtin.number.decimal.LessOrEqualMethodGen - .makeFunction(language)); - scope.registerMethod( - decimal, - "to_decimal", - org.enso.interpreter.node.expression.builtin.number.decimal.ToDecimalMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "floor", - org.enso.interpreter.node.expression.builtin.number.decimal.FloorMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "ceil", - org.enso.interpreter.node.expression.builtin.number.decimal.CeilMethodGen.makeFunction( - language)); - scope.registerMethod( - decimal, - "compare_to", - org.enso.interpreter.node.expression.builtin.number.decimal.CompareToMethodGen.makeFunction( - language)); + public Number(Builtins builtins) { + this.builtins = builtins; } /** @return the Int64 atom constructor. */ public AtomConstructor getSmallInteger() { + if (smallInteger == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + smallInteger = builtins.getBuiltinType(SmallInteger.class); + } return smallInteger; } /** @return the Big_Integer atom constructor. */ public AtomConstructor getBigInteger() { + if (bigInteger == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + bigInteger = builtins.getBuiltinType(BigInteger.class); + } return bigInteger; } /** @return the Integer atom constructor */ public AtomConstructor getInteger() { + if (integer == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + integer = builtins.getBuiltinType(Integer.class); + } return integer; } /** @return the Number atom constructor */ public AtomConstructor getNumber() { + if (number == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + number = builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.number.Number.class); + } return number; } /** @return the Decimal atom constructor */ public AtomConstructor getDecimal() { + if (decimal == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + decimal = builtins.getBuiltinType(Decimal.class); + } return decimal; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index ccc0472b93e8..38d1c067c11c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -5,15 +5,15 @@ public class Constants { public static final String ANY = "Standard.Base.Data.Any.Any"; public static final String ARRAY = "Standard.Base.Data.Array.Array"; - public static final String BOOLEAN = "Standard.Builtins.Data.Boolean.Boolean"; - public static final String DECIMAL = "Standard.Builtins.Main.Decimal"; + public static final String BOOLEAN = "Standard.Base.Data.Boolean.Boolean"; + public static final String DECIMAL = "Standard.Base.Data.Number.Internal.Decimal"; public static final String ERROR = "Standard.Base.Error.Common.Error"; public static final String FUNCTION = "Standard.Base.Function.Function"; - public static final String INTEGER = "Standard.Builtins.Main.Integer"; - public static final String MANAGED_RESOURCE = "Standard.Builtins.Main.Managed_Resource"; + public static final String INTEGER = "Standard.Base.Data.Number.Internal.Integer"; + public static final String MANAGED_RESOURCE = "Standard.Base.Runtime.Resource.Managed_Resource"; public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; public static final String NOTHING = "Standard.Base.Nothing.Nothing"; - public static final String NUMBER = "Standard.Builtins.Main.Number"; + public static final String NUMBER = "Standard.Base.Data.Number.Internal.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; public static final String TEXT = "Standard.Base.Data.Text"; diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso index 37ddfb3ed224..0a4ddbc1d897 100644 --- a/engine/runtime/src/main/resources/Builtins.enso +++ b/engine/runtime/src/main/resources/Builtins.enso @@ -3,666 +3,3 @@ # When adding a new builtin it is very important that you also define the stub # for that builtin in this file. If that is not done, it will fail to resolve # properly at runtime. - -## The root type of the Enso numeric hierarchy. - - If a Number is expected, then the program can provide either a Decimal or - an Integer in its place. -type Number - - ## The root type of the Enso numeric hierarchy. - - If a Number is expected, then the program can provide either a Decimal or - an Integer in its place. - @Builtin_Type - type Number - - ## ALIAS Add - - Adds two arbitrary numbers. - - Arguments: - - that: The number to add to this. - - Addition in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Adding 10 and 15. - - 10 + 15 - + : Number -> Number - + that = @Builtin_Method "Integer.+" - - ## ALIAS Subtract - - Subtract an arbitrary number from this. - - Arguments: - - that: The number to subtract from this. - - > Example - Subtract 5 from 2. - - 2 - 5 - - : Number -> Number - - that = @Builtin_Method "Integer.-" - - ## ALIAS Multiply - - Multiply two arbitrary numbers. - - Arguments: - - that: The number to multiply this by. - - Multiplication in Enso will undergo automatic conversions such that you - need not convert between Integer and Decimal manually. - - > Example - Multiplying 3 by 5. - - 3 * 5 - * : Number -> Number - * that = @Builtin_Method "Integer.*" - - ## ALIAS Divide - - Divides an this by an arbitrary number. - - Arguments: - - that: The number to divide this by. - - Division in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Dividing 10 by 4 to get 2.5. - - 10 / 4 - / : Number -> Number - / that = @Builtin_Method "Integer./" - - ## ALIAS Power - - Compute the result of raising this to the power that. - - Arguments: - - that: The exponent. - - > Example - Computing 2 cubed. - - 2^3 - ^ : Number -> Number - ^ that = @Builtin_Method "Integer.^" - -## Integral numbers. -type Integer - - ## Integer is the type of integral numbers in Enso. They are of unbounded - size and can grow as large as necessary. - - ? Representation - For certain operations (such as bitwise logic), the underlying - representation of the number matters. Enso Integers are represented as - signed 2's complement numbers. - - ? Performance - Integers that fit into 64 bits are represented in memory as 64 bits. - This means that operations on them achieve excellent performance. Once - the integer grows beyond being able to fit in 64 bits, performance will - degrade. - @Builtin_Type - type Integer - - ## Adds an integer and an arbitrary number. - - Arguments: - - that: The number to add to this. - - Addition in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Adding 10 and 15. - - 10 + 15 - + : Number -> Number - + that = @Builtin_Method "Integer.+" - - ## Subtract an arbitrary number from this. - - Arguments: - - that: The number to subtract from this. - - > Example - Subtract 5 from 2. - - 2 - 5 - - : Number -> Number - - that = @Builtin_Method "Integer.-" - - ## Multiply an integer by an arbitrary number. - - Arguments: - - that: The number to multiply this by. - - Multiplication in Enso will undergo automatic conversions such that you - need not convert between Integer and Decimal manually. - - > Example - Multiplying 3 by 5. - - 3 * 5 - * : Number -> Number - * that = @Builtin_Method "Integer.*" - - ## Divides an integer by an arbitrary number. - - Arguments: - - that: The number to divide this by. - - Division in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Dividing 10 by 4 to get 2.5. - - 10 / 4 - / : Number -> Number - / that = @Builtin_Method "Integer./" - - ## Computes the remainder when dividing this by that. - - Arguments: - - that: The number to divide this by. - - Modulus in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - Returns an error if the shift amount exceeds 2^32. - - > Example - Computing the remainder when dividing 10 by 3 (which is 1). - - 10 % 3 - % : Number -> Number ! Arithmetic_Error - % that = @Builtin_Method "Integer.%" - - ## Compute the result of raising this to the power that. - - Arguments: - - that: The exponent. - - > Example - Computing 2 cubed. - - 2^3 - ^ : Number -> Number - ^ that = @Builtin_Method "Integer.^" - - ## Compares this and that for equality. - - Arguments: - - that: The number to compare this against. - - > Example - Comparing 7 and 2 for equality. - - 7 == 2 - == : Number -> Boolean - == that = @Builtin_Method "Integer.==" - - ## Checks if this is greater than that. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is greater than 7. - - 10 > 7 - > : Number -> Boolean - > that = @Builtin_Method "Integer.>" - - ## Checks if this is greater than or equal to thatthat. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is greater than or equal to 7. - - 10 >= 7 - >= : Number -> Boolean - >= that = @Builtin_Method "Integer.>=" - - ## Checks if this is less than that. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is less than 7. - - 10 < 7 - < : Number -> Boolean - < that = @Builtin_Method "Integer.<" - - ## Checks if this is less than or equal to thatthat. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is less than or equal to 7. - - 10 <= 7 - <= : Number -> Boolean - <= that = @Builtin_Method "Integer.<=" - - ## Computes the absolute value of this. - - The absolute value of a positive number is itself, while the absolute - value of a negative number is that number multiplied by -1. - - > Example - Computing the absolute value of -10. - - -10.abs - abs : Integer - abs = @Builtin_Method "Integer.abs" - - ## Computes the nearest integer above this integer. - - This is a no-op on integers but is provided for completeness of the Enso - number API. - - > Example - Computing the ceiling of 4. - - 4.ceil - ceil : Integer - ceil = @Builtin_Method "Integer.ceil" - - ## Compares the two operands to determine the ordering of this with - respect to that. - - Arguments: - - that: The operand to order this with respect to. - - > Example - Computing the ordering of 1 and 4 (Less). - - 1.compare_to 4 - compare_to : Number -> Ordering - compare_to that = @Builtin_Method "Integer.compare_to" - - ## Computes the integer division of this by that. - - Arguments: - - that: The number to divide this by. - - Integer division rounds down to the nearest integer. - - Returns an error if `that` is zero. - - > Example - Dividing 10 by 3 to get 3. - - 10.div 3 - div : Integer -> Number ! Arithmetic_Error - div that = @Builtin_Method "Integer.div" - - ## Computes the nearest integer below this integer. - - This is a no-op on integers but is provided for completeness of the Enso - number API. - - > Example - Computing the floor of 4. - - 4.floor - floor : Integer - floor = @Builtin_Method "Integer.floor" - - ## Compute the negation of this. - - > Example - Negate 5 to get -5. - - 5.negate - negate : Integer - negate = @Builtin_Method "Integer.negate" - - ## Convert this to a decimal. - - > Example - Convert 5 to a decimal to get 5.0. - - 5.to_decimal - to_decimal : Decimal - to_decimal = @Builtin_Method "Integer.to_decimal" - - ## Computes the bitwise and (conjunction) operation between this and - that. - - Arguments: - - that: The number to compute the bitwise conjunction with. - - Bitwise and computes the logical conjunction of the corresponding pairs - of bits in the operands. - - ? Example - Computing the bitwise conjunction of 2_01101101 and 2_11110000. - - 2_01101101.bit_and 2_11110000 - bit_and : Integer -> Integer - bit_and that = @Builtin_Method "Integer.bit_and" - - ## Computes the bitewise compliment of this. - - The bitwise compliment negates the value of each bit in the operand. - - ? Example - Bitwise negation of 2_0110. - - 2_0110.bit_not - bit_not : Integer - bit_not = @Builtin_Method "Integer.bit_not" - - ## Computes the bitwise or (disjunction) operation between this and - that. - - Arguments: - - that: The number to compute the bitwise disjunction with. - - Bitwise or computes the logical disjunction of the pairs of corresponding - bits in the operands. - - > Example - Computing the bitwise disjunction of 2_01101101 and 2_11110000. - - 2_01101101.bit_or 2_11110000 - bit_or : Integer -> Integer - bit_or that = @Builtin_Method "Integer.bit_or" - - ## Computes the bitwise exclusive or between this and that. - - Arguments: - - that: The number to compute the bitwise exclusive or with. - - Bitwise exclusive or computes the exclusive or of the pairs of - corresponding bits in the operands. - - > Example - Computing the bitwise exclusive or of 2_01101101 and 2_11110000. - - 2_01101101.bit_xor 2_11110000 - bit_xor : Integer -> Integer - bit_xor that = @Builtin_Method "Integer.bit_xor" - - ## Shifts the bits of this by the amount that. - - Arguments: - - that: The number of bits by which the shift should be performed. - Positive numbers perform a left shift, while negative numbers perform a - right shift. - - Leftwise bit shifts fill the new bits with zeroes, while rightwise bit - shifts perform sign extension. - - Returns an error if the shift amount exceeds 2^32. - - > Example - Shift the bits of the number 1 left by four bits. - - 1.bit_shift 4 - bit_shift : Integer -> Integer ! Arithmetic_Error - bit_shift that = @Builtin_Method "Integer.bit_shift" - - ## Performs a left-wise bit shift on the bits of this. - - Arguments: - - that: The number of bits by which the shift should be performed. - Positive numbers perform a left shift, while negative numbers perform a - right shift. - - Leftwise bit shifts fill the new bits with zeroes, while rightwise bit - shifts perform sign extension. - - Returns an error if the shift amount exceeds 2^32. - - > Example - Shift the bits of the number 1 left by four bits. - - 1.bit_shift_l 4 - bit_shift_l : Integer -> Integer ! Arithmetic_Error - bit_shift_l that = @Builtin_Method "Integer.bit_shift_l" - - ## Performs a right-wise bit shift on the bits of this. - - Arguments: - - that: The number of bits by which the shift should be performed. - Positive numbers perform a right shift, while negative numbers perform - a left shift. - - Leftwise bit shifts fill the new bits with zeroes, while rightwise bit - shifts perform sign extension. - - Returns an error if the shift amount exceeds 2^32. - - > Example - Shift the bits of the number 1 right by four bits. - - 1.bit_shift_r 4 - bit_shift_r : Integer -> Integer ! Arithmetic_Error - bit_shift_r that = @Builtin_Method "Integer.bpit_shift_r" - -## Decimal numbers. -type Decimal - - ## Decimal is the type of decimal numbers in Enso. - - ? Representation - Enso's decimal numbers are represented as IEEE754 double-precision - floating point numbers. - @Builtin_Type - type Decimal - - ## Adds a deceimal and an arbitrary number. - - Arguments: - - that: The number to add to this. - - Addition in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Adding 10.1 and 15. - - 10.1 + 15 - + : Number -> Number - + that = @Builtin_Method "Decimal.+" - - ## Subtract an arbitrary number from this. - - Arguments: - - that: The number to subtract from this. - - > Example - Subtract 5 from 2.78. - - 2.78 - 5 - - : Number -> Number - - that = @Builtin_Method "Decimal.-" - - ## Multiply a decimal by an arbitrary number. - - Arguments: - - that: The number to multiply this by. - - Multiplication in Enso will undergo automatic conversions such that you - need not convert between Integer and Decimal manually. - - > Example - Multiplying 3 by 5.27. - - 5.27 * 3 - * : Number -> Number - * that = @Builtin_Method "Decimal.*" - - ## Divides a decimal by an arbitrary number. - - Arguments: - - that: The number to divide this by. - - Division in Enso will undergo automatic conversions such that you need - not convert between Integer and Decimal manually. - - > Example - Dividing 10 by 4.5. - - 10 / 4.5 - / : Number -> Number - / that = @Builtin_Method "Decimal./" - - ## Compute the result of raising this to the power that. - - Arguments: - - that: The exponent. - - > Example - Computing 2.2 cubed. - - 2.2^3 - ^ : Number -> Number - ^ that = @Builtin_Method "Decimal.^" - - ## Compares this and that for equality. - - Arguments: - - that: The number to compare this against. - - > Example - Comparing 7 and 2.1 for equality. - - 7 == 2.1 - == : Number -> Boolean - == that = @Builtin_Method "Decimal.==" - - ## Checks if this is greater than that. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is greater than 7.3. - - 10 > 7.3 - > : Number -> Boolean - > that = @Builtin_Method "Decimal.>" - - ## Checks if this is greater than or equal to thatthat. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is greater than or equal to 7.3. - - 10 >= 7.3 - >= : Number -> Boolean - >= that = @Builtin_Method "Decimal.>=" - - ## Checks if this is less than that. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10 is less than 7.3. - - 10 < 7.3 - < : Number -> Boolean - < that = @Builtin_Method "Decimal.<" - - ## Checks if this is less than or equal to thatthat. - - Arguments: - - that: The number to compare this against. - - > Example - Checking if 10.4 is less than or equal to 7. - - 10.4 <= 7 - <= : Number -> Boolean - <= that = @Builtin_Method "Decimal.<=" - - ## Computes the absolute value of this. - - The absolute value of a positive number is itself, while the absolute - value of a negative number is that number multiplied by -1. - - > Example - Computing the absolute value of -10.63. - - -10.63.abs - abs : Decimal - abs = @Builtin_Method "Decimal.abs" - - ## Computes the nearest integer above this number. - - This method provides a means of converting a Decimal to an Integer. - - > Example - Computing the ceiling of 4.736 (which is 5). - - 4.736.ceil - ceil : Integer - ceil = @Builtin_Method "Integer.ceil" - - ## Compares the two operands to determine the ordering of this with - respect to that. - - Arguments: - - that: The operand to order this with respect to. - - > Example - Computing the ordering of 1.732 and 4 (Less). - - 1.732.compare_to 4 - compare_to : Number -> Ordering - compare_to that = @Builtin_Method "Decimal.compare_to" - - ## Computes the nearest integer below this decimal. - - This method provides a means of converting a Decimal to an Integer. - - > Example - Computing the floor of 4.323 (which is 4). - - 4.323.floor - floor : Integer - floor = @Builtin_Method "Decimal.floor" - - ## Compute the negation of this. - - > Example - Negate 5.1 to get -5.1. - - 5.1.negate - negate : Decimal - negate = @Builtin_Method "Decimal.negate" - - ## Convert this to a decimal. - - This is a no-op on decimals, but is provided for completeness of the Enso - Number API. - - > Example - Convert 5.0 to a decimal to get 5.0. - - 5.0.to_decimal - to_decimal : Decimal - to_decimal = @Builtin_Method "Decimal.to_decimal" diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index fbeb5d462bb6..cf8ef8838cf3 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -39,6 +39,7 @@ import org.enso.compiler.core.IR.Name.Special import scala.collection.mutable import scala.collection.mutable.ArrayBuffer +import scala.jdk.OptionConverters._ /** This is an implementation of a codegeneration pass that lowers the Enso * [[IR]] into the truffle [[org.enso.compiler.core.Core.Node]] structures that @@ -245,8 +246,18 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => - val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) - builtinFunction.orElseThrow(() => new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) + // Builtin Types Number and Integer have methods only for documentation purposes + val ignore = + cons == context.getBuiltins.number().getNumber || + cons == context.getBuiltins.number().getInteger + if (ignore) Right(None) + else { + val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) + builtinFunction + .toScala + .map(Some(_)) + .toRight(new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) + } case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) @@ -260,17 +271,24 @@ class IrToTruffle( methodDef.methodName.name ) val callTarget = Truffle.getRuntime.createCallTarget(rootNode) - new RuntimeFunction( + Right(Some(new RuntimeFunction( callTarget, null, new FunctionSchema(arguments: _*) - ) + ))) case _ => - throw new CompilerError( + Left(new CompilerError( "Method bodies must be functions at the point of codegen." - ) + )) + } + function match { + case Left(failure) => + throw failure + case Right(Some(fun)) => + moduleScope.registerMethod(cons, methodDef.methodName.name, fun) + case _ => + // Don't register dummy function nodes } - moduleScope.registerMethod(cons, methodDef.methodName.name, function) } }) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 6137a0be4b25..e5399a8b4cdd 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -105,7 +105,7 @@ class ReplTest extends InterpreterTest with BeforeAndAfter with EitherValues { """ |import Standard.Base.Runtime.Debug |import Standard.Base.Runtime.State - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import Number | |run = | State.put Number 10 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 7c70f0f4f2cb..61fa1f2b3353 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -110,16 +110,16 @@ class RuntimeServerTest val metadata = new Metadata - val idMainX = metadata.addItem(51, 1) - val idMainY = metadata.addItem(61, 7) - val idMainZ = metadata.addItem(77, 5) - val idFooY = metadata.addItem(116, 8) - val idFooZ = metadata.addItem(133, 5) + val idMainX = metadata.addItem(71, 1) + val idMainY = metadata.addItem(81, 7) + val idMainZ = metadata.addItem(97, 5) + val idFooY = metadata.addItem(136, 8) + val idFooZ = metadata.addItem(153, 5) def code = metadata.appendToCode( """ - |from Standard.Builtins import all + |from Standard.Base.Data.Number.Internal import Number | |main = | x = 6 @@ -361,7 +361,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -732,11 +732,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(101, 41) - val idMainBar = metadata.addItem(133, 8) + val idMain = metadata.addItem(121, 41) + val idMainBar = metadata.addItem(153, 8) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.IO |import Standard.Base.Runtime.State | @@ -793,11 +793,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(101, 40) - val idMainBar = metadata.addItem(132, 8) + val idMain = metadata.addItem(121, 40) + val idMainBar = metadata.addItem(152, 8) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.IO |import Standard.Base.Runtime.State | @@ -1033,7 +1033,7 @@ class RuntimeServerTest val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val idMain = context.Main.metadata.addItem(42, 47) + val idMain = context.Main.metadata.addItem(62, 47) val contents = context.Main.code val mainFile = context.writeMain(contents) @@ -1063,7 +1063,7 @@ class RuntimeServerTest ) ) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1180,19 +1180,19 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(65, 35) - val idMainA = metadata.addItem(74, 8) - val idMainP = metadata.addItem(87, 12) + val idMain = metadata.addItem(85, 35) + val idMainA = metadata.addItem(94, 8) + val idMainP = metadata.addItem(107, 12) // pie id - metadata.addItem(99 + 8, 1) + metadata.addItem(127, 1) // uwu id - metadata.addItem(107 + 8, 1) + metadata.addItem(135, 1) // hie id - metadata.addItem(115 + 8, 6) + metadata.addItem(143, 6) // Number.x id - metadata.addItem(135 + 8, 1) + metadata.addItem(163, 1) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.IO | |main = @@ -1386,15 +1386,15 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(113, 88) - val id1 = metadata.addItem(122, 15) - val id2 = metadata.addItem(142, 18) - val id3 = metadata.addItem(165, 15) + val idMain = metadata.addItem(130, 88) + val id1 = metadata.addItem(139, 15) + val id2 = metadata.addItem(159, 18) + val id3 = metadata.addItem(182, 15) // Note that Nothing.Nothing is on purpose. // If not provided the full name it will resolve the // expression type of Nothing to a Nothing module val code = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import Number |from Standard.Base.Data.Text import all |import Standard.Base.Nothing | @@ -1575,7 +1575,7 @@ class RuntimeServerTest Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") ), TestMessages.update( - contextId, + contextId, id3, Constants.INTEGER, Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") @@ -1770,7 +1770,7 @@ class RuntimeServerTest val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val idMain = context.Main.metadata.addItem(42, 47) + val idMain = context.Main.metadata.addItem(62, 47) val mainFile = context.writeMain(context.Main.code) @@ -1795,7 +1795,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1849,7 +1849,7 @@ class RuntimeServerTest ) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.IO | |main = IO.println "I'm a file!" @@ -1886,7 +1886,7 @@ class RuntimeServerTest /* Modify the file: - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.IO | |Number.lucky = 42 @@ -1950,7 +1950,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1996,7 +1996,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -2048,7 +2048,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -2154,7 +2154,7 @@ class RuntimeServerTest ) ) ) - context.receiveN(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2205,7 +2205,7 @@ class RuntimeServerTest ) ) ) - context.receiveN(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2448,7 +2448,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number | |main = Number.pi |""".stripMargin.linesIterator.mkString("\n") @@ -2481,7 +2481,7 @@ class RuntimeServerTest ) ) ) - context.receiveN(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -3127,7 +3127,7 @@ class RuntimeServerTest ) ) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index f36e49bc7682..9b4d965f77fe 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -726,7 +726,7 @@ class RuntimeSuggestionUpdatesTest val moduleName = "Enso_Test.Test.Main" val contents = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.Data.Text |import Standard.Base.Nothing | @@ -909,7 +909,7 @@ class RuntimeSuggestionUpdatesTest |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") val aCode = - """from Standard.Builtins import Integer + """from Standard.Base.Data.Number.Internal import Integer | |type MyType | type MkA a diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 7737dcbc81dc..a7a9bb38c38a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -109,16 +109,16 @@ class RuntimeVisualisationsTest val metadata = new Metadata - val idMainX = metadata.addItem(51, 1) - val idMainY = metadata.addItem(61, 7) - val idMainZ = metadata.addItem(77, 5) - val idFooY = metadata.addItem(116, 8) - val idFooZ = metadata.addItem(133, 5) + val idMainX = metadata.addItem(71, 1) + val idMainY = metadata.addItem(81, 7) + val idMainZ = metadata.addItem(97, 5) + val idFooY = metadata.addItem(136, 8) + val idFooZ = metadata.addItem(153, 5) def code = metadata.appendToCode( """ - |from Standard.Builtins import all + |from Standard.Base.Data.Number.Internal import Number | |main = | x = 6 @@ -248,7 +248,7 @@ class RuntimeVisualisationsTest } it should "emit visualisation update when expression is computed" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMainRes = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -289,12 +289,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMainRes, Constants.INTEGER), context.executionComplete(contextId) ) @@ -304,7 +304,7 @@ class RuntimeVisualisationsTest requestId, Api.AttachVisualisation( visualisationId, - idMain, + idMainRes, Api.VisualisationConfiguration( contextId, "Enso_Test.Test.Visualisation", @@ -325,7 +325,7 @@ class RuntimeVisualisationsTest Api.VisualisationContext( `visualisationId`, `contextId`, - `idMain` + `idMainRes` ), data ) @@ -351,7 +351,7 @@ class RuntimeVisualisationsTest Api.VisualisationContext( `visualisationId`, `contextId`, - `idMain` + `idMainRes` ), data ) @@ -402,7 +402,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -531,7 +531,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -653,7 +653,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -773,7 +773,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -919,7 +919,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val pushResponses = context.receiveN(6) + val pushResponses = context.receiveNIgnoreStdLib(6) pushResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), @@ -1029,7 +1029,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1133,7 +1133,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1227,7 +1227,7 @@ class RuntimeVisualisationsTest } it should "return ModuleNotFound error when attaching visualisation" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMain = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1257,7 +1257,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1287,7 +1287,7 @@ class RuntimeVisualisationsTest } it should "be able to use external libraries if they are needed by the visualisation" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMain = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1317,7 +1317,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1375,7 +1375,7 @@ class RuntimeVisualisationsTest } it should "return VisualisationExpressionFailed error when attaching visualisation" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMain = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1405,7 +1405,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1449,7 +1449,7 @@ class RuntimeVisualisationsTest } it should "return visualisation evaluation errors with diagnostic info" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMain = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1479,7 +1479,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), @@ -1536,7 +1536,7 @@ class RuntimeVisualisationsTest } it should "return visualisation error with a stack trace" in { - val idMain = context.Main.metadata.addItem(87, 1) + val idMain = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1584,7 +1584,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receiveN(6) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 87b0650b9061..44bdaa7c1faa 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -57,7 +57,7 @@ class InteropTest extends InterpreterTest { "work with unresolved symbols" in { val code = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import all |from Standard.Base.Data.Text import all | |Number.add x = x + this diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala index 349f5f960aff..231aa1f49fa4 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala @@ -50,7 +50,7 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work with mixfix functions" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import all | |Number.if_then_else = ~t -> ~f -> if this == 0 then t else f | @@ -142,9 +142,9 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work properly when used with dot notation" in { val code = """ - |import Standard.Builtins + |from Standard.Base.Data.Number.Internal import Number | - |Builtins.Number.f = this + 10 + |Number.f = this + 10 | |main = | fun = _.f @@ -157,8 +157,6 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work properly when used inside the function of an application" in { val code = """ - |import Standard.Builtins - | |main = (_ - 5) 0 |""".stripMargin diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index 6b85b4638246..855a1d7acee3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -134,7 +134,7 @@ class LambdaTest extends InterpreterTest { "call fully saturated lambdas returned with TCO" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Number.Internal import Number | |Number.if_then_else = ~t -> ~f -> if this == 0 then t else f | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index 2ab2a40d156c..308bf9f8710c 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -12,7 +12,7 @@ class StateTest extends InterpreterTest { "be accessible from functions" in { val code = """import Standard.Base.Runtime.State - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import Number | |stateful = | State.put Number 10 @@ -29,7 +29,7 @@ class StateTest extends InterpreterTest { "be implicitly threaded through function executions" in { val code = """import Standard.Base.Runtime.State - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import Number | |inc_state = | x = State.get Number @@ -52,7 +52,7 @@ class StateTest extends InterpreterTest { "work well with recursive code" in { val code = """import Standard.Base.Runtime.State - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import Number | |main = | stateSum = n -> @@ -67,7 +67,7 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Builtins import Number + """from Standard.Base.Data.Number.Internal import Number |from Standard.Base.Data.List import Nil |import Standard.Base.IO |import Standard.Base.Nothing @@ -117,7 +117,7 @@ class StateTest extends InterpreterTest { "localize properly with State.run when 1 key used" in { val code = """import Standard.Base.Runtime.State - |from Standard.Builtins import Number + |from Standard.Base.Data.Number.Internal import Number | |inner = State.put Number 0 | diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinMethod.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinMethod.java index da182696c980..fa9d76742a1b 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinMethod.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinMethod.java @@ -17,4 +17,7 @@ /** @return a short description of this method. */ String description() default ""; + + /** @return a list of aliases (names) of this method */ + String aliases() default ""; } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index 8f85301dedab..8ffa0517a008 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -71,6 +71,12 @@ public boolean handleProcess(Set annotations, RoundEnviro } String fullClassName = def.getPackageName() + "." + def.getClassName(); registerBuiltinMethod(processingEnv.getFiler(), def.getDeclaredName(), fullClassName); + if (def.hasAliases()) { + for (String alias: def.aliases()) { + registerBuiltinMethod(processingEnv.getFiler(), alias, fullClassName); + } + } + } catch (IOException e) { e.printStackTrace(); } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index 3541384d0897..677fc8704e31 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -51,6 +51,22 @@ public MethodDefinition(String packageName, TypeElement element, ExecutableEleme this.constructorExpression = initConstructor(element); } + public boolean hasAliases() { + return !annotation.aliases().isEmpty(); + } + + public String[] aliases() { + if (annotation.aliases().isEmpty()) { + return new String[0]; + } else { + String[] methodNames = annotation.aliases().split(","); + for (int i=0; i Nothing Test.specify "should allow to get the source location of a frame" pending=location_pending <| src = Meta.get_source_location 0 - loc = "Meta_Spec.enso:83:15-40" + loc = "Meta_Spec.enso:85:15-40" src.take (Last loc.length) . should_equal loc Test.specify "should allow to get qualified type names of values" <| From da040f8b70abd897ebc1472a1e5e2dfd6cd9722a Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 09:50:23 +0200 Subject: [PATCH 44/73] Missed some test adaptation --- test/Tests/src/Semantic/Meta_Spec.enso | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Tests/src/Semantic/Meta_Spec.enso b/test/Tests/src/Semantic/Meta_Spec.enso index fae229ef8852..f9c913223239 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -81,13 +81,13 @@ spec = Test.group "Meta-Value Manipulation" <| _ -> Nothing Test.specify "should allow to get the source location of a frame" pending=location_pending <| src = Meta.get_source_location 0 - loc = "Meta_Spec.enso:85:15-40" + loc = "Meta_Spec.enso:83:15-40" src.take (Last loc.length) . should_equal loc Test.specify "should allow to get qualified type names of values" <| x = 42 y = My_Type 1 2 3 - Meta.get_qualified_type_name x . should_equal "Standard.Builtins.Main.Integer" + Meta.get_qualified_type_name x . should_equal "Standard.Base.Data.Number.Internal.Integer" Meta.get_qualified_type_name y . should_equal "enso_dev.Tests.Semantic.Meta_Spec.My_Type" Test.specify "should allow access to package names" <| From 4e4535efe91f16f65d595ca5f70e628e381d94d5 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 11:01:39 +0200 Subject: [PATCH 45/73] Getting rid of Standard.Builtins mentions --- .../0.0.0-dev/src/Data/Noise/Generator.enso | 1 - .../0.0.0-dev/src/Data/Text/Extensions.enso | 2 - .../Base/0.0.0-dev/src/Data/Text/Regex.enso | 2 - .../0.0.0-dev/src/Data/Text/Regex/Engine.enso | 3 +- .../src/Data/Text/Regex/Engine/Default.enso | 2 - .../Base/0.0.0-dev/src/Error/Common.enso | 4 +- .../Base/0.0.0-dev/src/Error/Extensions.enso | 6 -- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 - .../Database/0.0.0-dev/src/Data/Dialect.enso | 1 - .../Standard/Searcher/0.0.0-dev/src/Main.enso | 2 - .../src/Internal/Vector_Builder.enso | 2 - .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 2 - .../0.0.0-dev/src/Sql/Visualization.enso | 8 +-- .../search/DocSectionsBuilderTest.scala | 6 +- .../interpreter/runtime/type/Constants.java | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 21 +++--- .../test/resources/Cycle_Test/src/Main.enso | 2 +- .../instrument/RuntimeInstrumentTest.scala | 4 +- .../test/instrument/RuntimeServerTest.scala | 72 ++++++++----------- .../test/semantic/JavaInteropTest.scala | 2 - .../test/semantic/PolyglotTest.scala | 4 -- .../interpreter/test/semantic/TextTest.scala | 3 +- test/Benchmarks/src/Collections.enso | 1 - test/Visualization_Tests/src/Sql_Spec.enso | 4 +- tools/ci/Test.enso | 2 +- 25 files changed, 56 insertions(+), 104 deletions(-) delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Noise/Generator.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Noise/Generator.enso index e5baffd38afe..938215de0fe3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Noise/Generator.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Noise/Generator.enso @@ -1,7 +1,6 @@ from Standard.Base import all import Standard.Base.Data.Interval.Bound -import Standard.Base.Error.Extensions polyglot java import java.lang.Long polyglot java import java.util.Random diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso index a6f8b27a80e3..c42f4dca558e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso @@ -14,8 +14,6 @@ import Standard.Base.Data.Text.Text_Sub_Range import Standard.Base.Data.Locale import Standard.Base.Meta -from Standard.Builtins export Text - export Standard.Base.Data.Text.Matching_Mode export Standard.Base.Data.Text.Case export Standard.Base.Data.Text.Location diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex.enso index 0fa951ac2118..953baa981f37 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex.enso @@ -15,8 +15,6 @@ import Standard.Base.Data.Text.Regex.Option import Standard.Base.Data.Text.Split_Kind import Standard.Base.Data.Map -import Standard.Base.Error.Extensions as Errors - ## Compile the provided `expression` into a regex pattern that can be used for matching. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine.enso index cede644395aa..9f2d85041a5e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine.enso @@ -17,8 +17,7 @@ customisable `Engine` and `Pattern` types. from Standard.Base import all - -import Standard.Base.Error.Extensions as Errors +import Standard.Base.Error.Common as Errors from Standard.Base.Data.Text.Regex.Engine.Default as Default_Engine export Default diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso index 5a9cd3f7d5b7..caf17ef89058 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso @@ -42,8 +42,6 @@ import Standard.Base.Data.Text.Regex.Mode import Standard.Base.Polyglot.Java from Standard.Base.Data.Text.Span as Span_Module import Utf_16_Span -import Standard.Base.Error.Extensions as Errors - polyglot java import java.lang.IllegalArgumentException polyglot java import java.lang.IndexOutOfBoundsException polyglot java import java.lang.StringBuffer diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index cfe6f62fd5ee..795c1ac46b6c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -553,8 +553,8 @@ Unimplemented_Error.to_display_text = "An implementation is missing: " + this.me > Example Throwing an error to show that something is unimplemented. - import Standard.Base.Error.Extensions + import Standard.Base.Error.Common as Errors - example_unimplemented = Extensions.unimplemented + example_unimplemented = Errors.unimplemented unimplemented : Text -> Void unimplemented message="" = Panic.throw (Unimplemented_Error message) \ No newline at end of file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso deleted file mode 100644 index cd4367e8d975..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso +++ /dev/null @@ -1,6 +0,0 @@ -from Standard.Base import all - -import Standard.Builtins - - - diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 9f03a723a927..452ddac8fc2d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -19,7 +19,6 @@ import project.Data.Text.Extensions import project.Data.Text.Matching import project.Data.Vector import project.Error.Common -import project.Error.Extensions import project.Function import project.IO.Prim_Io import project.IO @@ -78,7 +77,6 @@ from project.Data.Text.Extensions export Text, Split_Kind, Line_Ending_Style, Ca from project.Data.Text.Matching export Case_Insensitive, Text_Matcher, Regex_Matcher from project.Data.Text export all from project.Error.Common export all -from project.Error.Extensions export all from project.Function export all from project.Meta.Enso_Project export all from project.Nothing export all diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect.enso index 48cf0d582033..655ef87037a8 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect.enso @@ -1,6 +1,5 @@ from Standard.Base import all -import Standard.Base.Error.Extensions as Errors import Standard.Table.Data.Aggregate_Column import Standard.Database.Data.Sql import Standard.Database.Data.Dialect.Postgres diff --git a/distribution/lib/Standard/Searcher/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Searcher/0.0.0-dev/src/Main.enso index 512461427506..da450340cf0d 100644 --- a/distribution/lib/Standard/Searcher/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Searcher/0.0.0-dev/src/Main.enso @@ -8,8 +8,6 @@ from Standard.Base import all -import Standard.Base.Error.Extensions as Error - ## ALIAS Text Input Creating text in Enso is as simple as adding a node that contains the text diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Vector_Builder.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Vector_Builder.enso index f3eefe9b0051..96a19ed355cc 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Vector_Builder.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Vector_Builder.enso @@ -1,7 +1,5 @@ from Standard.Base import all -from Standard.Builtins import Array - ## PRIVATE An efficient builder for concatenating vectors. diff --git a/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso index 7f78c3bf9903..d874fab905c0 100644 --- a/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Test/0.0.0-dev/src/Main.enso @@ -2,8 +2,6 @@ from Standard.Base import all import Standard.Base.Runtime.State import Standard.Base.System -import Standard.Builtins - ## Creates a new test group, desribing properties of the object described by `this`. diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso index bf7b2a038cf2..40240452ca36 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso @@ -40,8 +40,8 @@ prepare_visualization x = Helpers.recover_errors <| types it will return `Nothing`. find_expected_enso_type_for_sql : Sql_Type -> Text find_expected_enso_type_for_sql sql_type = - if sql_type.is_definitely_integer then "Standard.Builtins.Main.Integer" else - if sql_type.is_definitely_double then "Standard.Builtins.Main.Decimal" else - if sql_type.is_definitely_text then "Standard.Builtins.Main.Text" else - if sql_type.is_definitely_boolean then "Standard.Builtins.Main.Boolean" else + if sql_type.is_definitely_integer then "Standard.Base.Data.Number.Internal.Integer" else + if sql_type.is_definitely_double then "Standard.Base.Data.Number.Internal.Decimal" else + if sql_type.is_definitely_text then "Standard.Base.Data.Text.Text" else + if sql_type.is_definitely_boolean then "Standard.Base.Boolean.Boolean" else Nothing diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/search/DocSectionsBuilderTest.scala b/engine/language-server/src/test/scala/org/enso/languageserver/search/DocSectionsBuilderTest.scala index b671e2e67ec3..50eeaad19a74 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/search/DocSectionsBuilderTest.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/search/DocSectionsBuilderTest.scala @@ -57,9 +57,9 @@ class DocSectionsBuilderTest extends AnyWordSpec with Matchers { | > Example | Throwing an error to show that something is unimplemented. | - | import Standard.Base.Error.Extensions + | import Standard.Base.Error.Common as Errors | - | example_unimplemented = Extensions.unimplemented + | example_unimplemented = Errors.unimplemented |""".stripMargin.linesIterator.mkString("\n") val expected = Seq( DocSection.Tag("ADVANCED", ""), @@ -73,7 +73,7 @@ class DocSectionsBuilderTest extends AnyWordSpec with Matchers { DocSection.Marked( DocSection.Mark.Example(), Some("Example"), - " Throwing an error to show that something is unimplemented.
import Standard.Base.Error.Extensions
example_unimplemented = Extensions.unimplemented
" + " Throwing an error to show that something is unimplemented.
import Standard.Base.Error.Common as Errors
example_unimplemented = Errors.unimplemented
" ) ) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 38d1c067c11c..486e72d22b91 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -16,7 +16,7 @@ public class Constants { public static final String NUMBER = "Standard.Base.Data.Number.Internal.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; - public static final String TEXT = "Standard.Base.Data.Text"; + public static final String TEXT = "Standard.Base.Data.Text.Text"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index cf8ef8838cf3..4f09bedfc563 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -246,18 +246,15 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => - // Builtin Types Number and Integer have methods only for documentation purposes - val ignore = - cons == context.getBuiltins.number().getNumber || - cons == context.getBuiltins.number().getInteger - if (ignore) Right(None) - else { - val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) - builtinFunction - .toScala - .map(Some(_)) - .toRight(new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) - } + val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) + builtinFunction + .toScala + .map(Some(_)) + .toRight(new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) + .left.flatMap( l => + // Builtin Types Number and Integer have methods only for documentation purposes + if (cons == context.getBuiltins.number().getNumber || + cons == context.getBuiltins.number().getInteger) Right(None) else Left(l)) case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) diff --git a/engine/runtime/src/test/resources/Cycle_Test/src/Main.enso b/engine/runtime/src/test/resources/Cycle_Test/src/Main.enso index 686abcb4ada2..f1502f63bc1e 100644 --- a/engine/runtime/src/test/resources/Cycle_Test/src/Main.enso +++ b/engine/runtime/src/test/resources/Cycle_Test/src/Main.enso @@ -1,4 +1,4 @@ import project.Sub.Imp -from Standard.Builtins import IO +from Standard.Base import all main = IO.println "Hello, World!" diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 84637d25f3c8..0f7afb9a054a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -742,9 +742,7 @@ class RuntimeInstrumentTest val mainRes = metadata.addItem(52, 1) val code = - """from Standard.Builtins import all - | - |main = + """main = | x = | f x = x + 1 | f 42 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 61fa1f2b3353..ac8d49b3a1a3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -497,17 +497,16 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(137, 121) - val idMainX = metadata.addItem(164, 8) - val idMainY = metadata.addItem(181, 8) - val idMainM = metadata.addItem(198, 5) - val idMainP = metadata.addItem(212, 5) - val idMainQ = metadata.addItem(226, 5) - val idMainF = metadata.addItem(248, 9) + val idMain = metadata.addItem(103, 121) + val idMainX = metadata.addItem(130, 8) + val idMainY = metadata.addItem(147, 8) + val idMainM = metadata.addItem(164, 5) + val idMainP = metadata.addItem(178, 5) + val idMainQ = metadata.addItem(192, 5) + val idMainF = metadata.addItem(214, 9) val code = - """from Standard.Builtins import all - |import Standard.Base.IO + """import Standard.Base.IO |import Enso_Test.Test.A | |type Quux @@ -530,8 +529,7 @@ class RuntimeServerTest val mainFile = context.writeMain(contents) val aCode = - """from Standard.Builtins import all - | + """ |type A | type A un_a | @@ -613,13 +611,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(58, 17) - val idMainFoo = metadata.addItem(63, 12) + val idMain = metadata.addItem(23, 17) + val idMainFoo = metadata.addItem(28, 12) val code = - """from Standard.Builtins import all - | - |foo a b = a + b + """foo a b = a + b | |main = | this.foo 1 2 @@ -856,13 +852,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(58, 23) - val idMainFoo = metadata.addItem(63, 12) + val idMain = metadata.addItem(23, 23) + val idMainFoo = metadata.addItem(28, 12) val code = - """from Standard.Builtins import all - | - |foo a b = a + b + """foo a b = a + b | |main = | this.foo 1 2 @@ -2577,9 +2571,8 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = this.foo + """main = + | this.foo | |foo = | x = this.bar @@ -2637,7 +2630,7 @@ class RuntimeServerTest "Main.baz", Some(mainFile), Some( - model.Range(model.Position(11, 8), model.Position(11, 17)) + model.Range(model.Position(10, 8), model.Position(10, 17)) ), None ), @@ -2645,7 +2638,7 @@ class RuntimeServerTest "Main.bar", Some(mainFile), Some( - model.Range(model.Position(8, 8), model.Position(8, 16)) + model.Range(model.Position(7, 8), model.Position(7, 16)) ), None ), @@ -2653,7 +2646,7 @@ class RuntimeServerTest "Main.foo", Some(mainFile), Some( - model.Range(model.Position(5, 8), model.Position(5, 16)) + model.Range(model.Position(4, 8), model.Position(4, 16)) ), None ), @@ -2661,7 +2654,7 @@ class RuntimeServerTest "Main.main", Some(mainFile), Some( - model.Range(model.Position(2, 7), model.Position(2, 15)) + model.Range(model.Position(1, 4), model.Position(1, 12)) ), None ) @@ -2681,10 +2674,9 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = x = 1 - |""".stripMargin.linesIterator.mkString("\n") + """main = + | x = 1 + |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) val mainFile = context.writeMain(contents) @@ -2723,7 +2715,7 @@ class RuntimeServerTest Api.ExecutionResult.Diagnostic.warning( "Unused variable x.", Some(mainFile), - Some(model.Range(model.Position(2, 7), model.Position(2, 8))), + Some(model.Range(model.Position(1, 4), model.Position(1, 5))), None ) ) @@ -2740,9 +2732,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |foo x = 1 + """foo x = 1 | |main = 42 |""".stripMargin.linesIterator.mkString("\n") @@ -2784,7 +2774,7 @@ class RuntimeServerTest Api.ExecutionResult.Diagnostic.warning( "Unused function argument x.", Some(mainFile), - Some(model.Range(model.Position(2, 4), model.Position(2, 5))) + Some(model.Range(model.Position(0, 4), model.Position(0, 5))) ) ) ) @@ -2800,9 +2790,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = + """main = | x = 1 | x = 2 |""".stripMargin.linesIterator.mkString("\n") @@ -2844,12 +2832,12 @@ class RuntimeServerTest Api.ExecutionResult.Diagnostic.warning( "Unused variable x.", Some(mainFile), - Some(model.Range(model.Position(3, 4), model.Position(3, 5))) + Some(model.Range(model.Position(1, 4), model.Position(1, 5))) ), Api.ExecutionResult.Diagnostic.error( "Variable x is being redefined.", Some(mainFile), - Some(model.Range(model.Position(4, 4), model.Position(4, 9))) + Some(model.Range(model.Position(2, 4), model.Position(2, 9))) ) ) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala index f7b5a7045ca6..7e0e3a8cb667 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala @@ -14,7 +14,6 @@ class JavaInteropTest extends InterpreterTest { val code = """ |polyglot java import org.enso.example.TestClass - |from Standard.Builtins import all | |main = TestClass.add 1 2 |""".stripMargin @@ -26,7 +25,6 @@ class JavaInteropTest extends InterpreterTest { val code = """ |polyglot java import org.enso.example.TestClass - |from Standard.Builtins import all | |main = | instance = TestClass.new (x -> x * 2) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index a15643064e4c..a372a454deed 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -60,7 +60,6 @@ class PolyglotTest extends InterpreterTest { "match on Polyglot type when imported everything from stdlib" in { val code = """from Standard.Base import all - |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -78,7 +77,6 @@ class PolyglotTest extends InterpreterTest { val code = """from Standard.Base.Polyglot import all |from Standard.Base.IO import all - |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -96,7 +94,6 @@ class PolyglotTest extends InterpreterTest { val code = """import Standard.Base.Polyglot |from Standard.Base.IO import all - |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = @@ -114,7 +111,6 @@ class PolyglotTest extends InterpreterTest { val code = """import Standard.Base.Polyglot |from Standard.Base.IO import all - |from Standard.Builtins import Nothing |polyglot java import java.util.Random | |main = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index e7c65e0da385..c92ea4bbb975 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala @@ -78,8 +78,7 @@ class TextTest extends InterpreterTest { "support printing to standard error" in { val code = - s"""from Standard.Builtins import all - |import Standard.Base.IO + s"""import Standard.Base.IO | |main = IO.print_err "My error string" |""".stripMargin diff --git a/test/Benchmarks/src/Collections.enso b/test/Benchmarks/src/Collections.enso index daa7fdddaee3..c49d63788cb6 100644 --- a/test/Benchmarks/src/Collections.enso +++ b/test/Benchmarks/src/Collections.enso @@ -1,6 +1,5 @@ from Standard.Base import all -import Standard.Builtins import Standard.Test.Bench polyglot java import java.util.Random diff --git a/test/Visualization_Tests/src/Sql_Spec.enso b/test/Visualization_Tests/src/Sql_Spec.enso index d8b50ecaa531..276a2c5bee7b 100644 --- a/test/Visualization_Tests/src/Sql_Spec.enso +++ b/test/Visualization_Tests/src/Sql_Spec.enso @@ -11,8 +11,8 @@ visualization_spec connection = Test.specify "should provide type metadata for interpolations" <| q = t.where ((t.at "B" == 2) && (t.at "A" == True)) . at "C" vis = Visualization.prepare_visualization q - int_param = Json.from_pairs [["value", 2], ["actual_type", "Standard.Builtins.Main.Integer"], ["expected_sql_type", "INTEGER"], ["expected_enso_type", "Standard.Builtins.Main.Integer"]] - str_param = Json.from_pairs [["value", True], ["actual_type", "Standard.Builtins.Main.Boolean"], ["expected_sql_type", "VARCHAR"], ["expected_enso_type", "Standard.Builtins.Main.Text"]] + int_param = Json.from_pairs [["value", 2], ["actual_type", "Standard.Base.Data.Number.Internal.Integer"], ["expected_sql_type", "INTEGER"], ["expected_enso_type", "Standard.Base.Data.Number.Internal.Integer"]] + str_param = Json.from_pairs [["value", True], ["actual_type", "Standard.Base.Data.Boolean.Boolean"], ["expected_sql_type", "VARCHAR"], ["expected_enso_type", "Standard.Base.Data.Text.Text"]] code = 'SELECT "T"."C" AS "C" FROM "T" AS "T" WHERE (("T"."B" = ?) AND ("T"."A" = ?))' json = Json.from_pairs [["dialect", "sqlite"], ["code", code], ["interpolations", [int_param, str_param]]] vis . should_equal json.to_text diff --git a/tools/ci/Test.enso b/tools/ci/Test.enso index 4aa532a0e1db..d51254279908 100644 --- a/tools/ci/Test.enso +++ b/tools/ci/Test.enso @@ -1,3 +1,3 @@ -from Standard.Builtins import all +from Standard.Base import all main = IO.println "Test successful." From 10d1a52358dc67ccec9134ebac6eabd971005f2e Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 11:14:43 +0200 Subject: [PATCH 46/73] Remove empty Builtins.enso references --- .../interpreter/runtime/builtin/Builtins.java | 16 ++-------------- engine/runtime/src/main/resources/Builtins.enso | 5 ----- 2 files changed, 2 insertions(+), 19 deletions(-) delete mode 100644 engine/runtime/src/main/resources/Builtins.enso diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 9cb93803b4ed..a804bff474c4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -41,7 +41,6 @@ public class Builtins { public static final String PACKAGE_NAME = "Builtins"; public static final String NAMESPACE = "Standard"; - public static final String SOURCE_NAME = PACKAGE_NAME + ".enso"; public static final String MODULE_NAME = NAMESPACE + "." + PACKAGE_NAME + ".Main"; /** Container for method names needed outside this class. */ @@ -122,9 +121,7 @@ public Builtins(Context context) { error = new Error(this); ordering = new Ordering(this); system = new System(this); - - // TODO: Builtins that are not yet moved to stdlib - number = new Number(this);//language, scope); + number = new Number(this); special = new Special(language); } @@ -166,16 +163,7 @@ public boolean isIrInitialized() { /** Initialize the source file for the builtins module. */ @CompilerDirectives.TruffleBoundary public void initializeBuiltinsSource() { - try { - var builtinsModuleBytes = - Objects.requireNonNull( - getClass().getClassLoader().getResourceAsStream(Builtins.SOURCE_NAME)) - .readAllBytes(); - String source = new String(builtinsModuleBytes, StandardCharsets.UTF_8); - module.setLiteralSource(source); - } catch (IOException e) { - throw new CompilerError("Fatal, unable to read Builtins source file."); - } + module.setLiteralSource(""); } /** diff --git a/engine/runtime/src/main/resources/Builtins.enso b/engine/runtime/src/main/resources/Builtins.enso deleted file mode 100644 index 0a4ddbc1d897..000000000000 --- a/engine/runtime/src/main/resources/Builtins.enso +++ /dev/null @@ -1,5 +0,0 @@ -# NOTE TO DEVELOPERS -# ================== -# When adding a new builtin it is very important that you also define the stub -# for that builtin in this file. If that is not done, it will fail to resolve -# properly at runtime. From 5ae3289cdc9e0abd2173d41fb8efbfb366e7075c Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 11:18:23 +0200 Subject: [PATCH 47/73] Automatic formatting Applied to reduce merge conflicts with `develop` branch --- .../boot/ResourcesInitialization.scala | 10 +- .../resource/DirectoriesInitialization.scala | 4 +- .../boot/resource/RepoInitialization.scala | 8 +- .../filemanager/FileSystem.scala | 8 +- .../filemanager/FileSystemApi.scala | 22 +- .../binary/factory/EnsoDigestFactory.scala | 10 +- .../file/ChecksumBytesHandler.scala | 8 +- .../file/ReadBytesHandler.scala | 10 +- .../binary/factory/FileSegmentFactory.scala | 14 +- .../factory/ReadBytesCommandFactory.scala | 10 +- .../enso/polyglot/ModuleManagementTest.scala | 103 +-- .../org/enso/interpreter/OptionsHelper.java | 3 +- .../org/enso/interpreter/epb/EpbLanguage.java | 4 +- .../epb/node/ContextRewrapExceptionNode.java | 3 +- .../epb/node/ContextRewrapNode.java | 3 +- .../interpreter/epb/node/ForeignEvalNode.java | 9 +- .../enso/interpreter/node/EnsoRootNode.java | 1 - .../callable/InteropConversionCallNode.java | 2 +- .../callable/dispatch/InvokeFunctionNode.java | 1 - .../callable/resolver/AnyResolverNode.java | 9 +- .../resolver/DataflowErrorResolverNode.java | 4 +- .../callable/resolver/HostMethodCallNode.java | 31 +- .../BooleanConstructorBranchNode.java | 19 +- .../node/controlflow/caseexpr/CaseNode.java | 6 +- .../caseexpr/PolyglotBranchNode.java | 5 +- .../node/expression/atom/InstantiateNode.java | 3 +- .../node/expression/builtin/Boolean.java | 6 +- .../node/expression/builtin/Builtin.java | 8 +- .../builtin/bool/CompareToNode.java | 48 +- .../expression/builtin/bool/EqualsNode.java | 5 +- .../expression/builtin/bool/IfThenNode.java | 3 +- .../builtin/debug/DebugBreakpointNode.java | 6 +- .../builtin/error/CatchAnyNode.java | 3 +- .../expression/builtin/error/CaughtPanic.java | 2 +- .../error/GetAttachedStackTraceNode.java | 3 +- .../error/InexhaustivePatternMatchError.java | 1 - .../builtin/error/InvalidArrayIndexError.java | 1 - .../error/InvalidConversionTargetError.java | 1 - .../builtin/error/ModuleDoesNotExist.java | 1 - .../ArityErrorToDisplayTextNode.java | 8 +- ...onversionTargetErrorToDisplayTextNode.java | 2 +- .../generic/IsLanguageInstalledNode.java | 5 +- .../interop/java/AddToClassPathNode.java | 5 +- .../builtin/interop/java/LookupClassNode.java | 4 +- .../interop/syntax/HostValueToEnsoNode.java | 4 +- .../expression/builtin/io/GetFileNode.java | 6 +- .../builtin/meta/ProjectDescription.java | 4 +- .../builtin/mutable/ComparatorNode.java | 9 +- .../expression/builtin/mutable/CopyNode.java | 19 +- .../builtin/mutable/GetRefNode.java | 5 +- .../expression/builtin/mutable/SortNode.java | 15 +- .../expression/builtin/number/BigInteger.java | 3 +- .../expression/builtin/number/Decimal.java | 4 +- .../expression/builtin/number/Integer.java | 3 +- .../expression/builtin/number/Number.java | 3 +- .../builtin/number/SmallInteger.java | 3 +- .../number/bigInteger/BitShiftNode.java | 14 +- .../number/bigInteger/BitShiftRightNode.java | 4 +- .../number/bigInteger/CompareToNode.java | 16 +- .../builtin/number/bigInteger/DivNode.java | 4 +- .../builtin/number/bigInteger/EqualsNode.java | 4 +- .../builtin/number/bigInteger/ModNode.java | 4 +- .../builtin/number/decimal/CompareToNode.java | 15 +- .../builtin/number/decimal/EqualsNode.java | 4 +- .../number/smallInteger/BitShiftNode.java | 13 +- .../number/smallInteger/CompareToNode.java | 15 +- .../number/smallInteger/EqualsNode.java | 4 +- .../builtin/number/utils/BigIntegerOps.java | 7 +- .../expression/builtin/ordering/Equal.java | 3 +- .../expression/builtin/ordering/Greater.java | 4 +- .../expression/builtin/ordering/Less.java | 4 +- .../expression/builtin/ordering/Ordering.java | 4 +- .../builtin/resource/ManagedResource.java | 3 +- .../builtin/resource/RegisterNode.java | 5 +- .../expression/builtin/resource/TakeNode.java | 3 +- .../expression/builtin/resource/WithNode.java | 6 +- .../builtin/state/GetStateNode.java | 11 +- .../builtin/state/PutStateNode.java | 15 +- .../builtin/system/CreateProcessNode.java | 3 +- .../builtin/system/SystemProcessResult.java | 3 +- .../node/expression/debug/EvalNode.java | 8 +- .../org/enso/interpreter/runtime/Context.java | 5 +- .../org/enso/interpreter/runtime/Module.java | 12 +- .../interpreter/runtime/ThreadManager.java | 20 +- .../interpreter/runtime/builtin/Builtins.java | 256 +++---- .../interpreter/runtime/builtin/Debug.java | 3 +- .../interpreter/runtime/builtin/Error.java | 60 +- .../interpreter/runtime/builtin/Number.java | 18 +- .../interpreter/runtime/builtin/Ordering.java | 20 +- .../callable/UnresolvedConversion.java | 4 +- .../runtime/callable/atom/Atom.java | 15 +- .../callable/atom/AtomConstructor.java | 62 +- .../runtime/callable/function/Function.java | 39 +- .../enso/interpreter/runtime/data/Array.java | 11 +- .../interpreter/runtime/data/text/Text.java | 8 +- .../runtime/error/DataflowError.java | 32 +- .../dispatch/DefaultBooleanExports.java | 103 ++- .../dispatch/DefaultDoubleExports.java | 8 +- .../library/dispatch/DefaultLongExports.java | 47 +- .../dispatch/MethodDispatchLibrary.java | 2 +- .../runtime/number/EnsoBigInteger.java | 8 +- .../runtime/scope/ModuleScope.java | 26 +- .../runtime/scope/TopLevelScope.java | 9 +- .../org/enso/compiler/codegen/AstView.scala | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 672 ++++++++++-------- .../scala/org/enso/compiler/core/IR.scala | 9 +- .../org/enso/compiler/data/BindingsMap.scala | 7 +- .../pass/analyse/BindingAnalysis.scala | 12 +- .../compiler/pass/desugar/ComplexType.scala | 9 +- .../compiler/pass/lint/UnusedBindings.scala | 24 +- .../pass/resolve/MethodDefinitions.scala | 6 +- .../pass/resolve/OverloadsResolution.scala | 4 +- .../command/DetachVisualisationCmd.scala | 10 +- .../command/ModifyVisualisationCmd.scala | 10 +- .../desugar/GenerateMethodBodiesTest.scala | 2 +- .../pass/desugar/OperatorToFunctionTest.scala | 3 +- .../optimise/ApplicationSaturationTest.scala | 6 +- .../resolve/DocumentationCommentsTest.scala | 6 +- .../pass/resolve/ModuleThisToHereTest.scala | 16 +- .../instrument/InstrumentTestContext.scala | 23 +- .../test/instrument/RuntimeErrorsTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 14 +- .../RuntimeVisualisationsTest.scala | 4 +- .../semantic/CompileDiagnosticsTest.scala | 4 +- .../test/semantic/DataflowErrorsTest.scala | 2 +- .../test/semantic/SystemProcessTest.scala | 4 +- .../org/enso/interpreter/dsl/BuiltinType.java | 13 +- .../dsl/BuiltinsMetadataProcessor.java | 123 ++-- .../enso/interpreter/dsl/MethodProcessor.java | 7 +- .../enso/interpreter/dsl/TypeProcessor.java | 123 ++-- .../dsl/model/MethodDefinition.java | 6 +- .../enso/logger/masking/MaskingFactory.java | 2 +- .../scala/org/enso/pkg/QualifiedName.scala | 6 +- .../LanguageServerProtocol.scala | 7 +- .../org/enso/syntax/text/spec/ParserDef.scala | 22 +- .../scala/org/enso/text/editing/model.scala | 2 +- 136 files changed, 1288 insertions(+), 1318 deletions(-) diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/ResourcesInitialization.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/ResourcesInitialization.scala index bd727c8bd06b..01781de57b7b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/ResourcesInitialization.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/ResourcesInitialization.scala @@ -29,11 +29,11 @@ object ResourcesInitialization { * @return the initialization component */ def apply( - eventStream: EventStream, - directoriesConfig: ProjectDirectoriesConfig, - suggestionsRepo: SqlSuggestionsRepo, - versionsRepo: SqlVersionsRepo, - truffleContext: Context + eventStream: EventStream, + directoriesConfig: ProjectDirectoriesConfig, + suggestionsRepo: SqlSuggestionsRepo, + versionsRepo: SqlVersionsRepo, + truffleContext: Context )(implicit ec: ExecutionContext): InitializationComponent = { val resources = Seq( new DirectoriesInitialization(directoriesConfig), diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/DirectoriesInitialization.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/DirectoriesInitialization.scala index 041ad054220e..9a4bfe7469ab 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/DirectoriesInitialization.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/DirectoriesInitialization.scala @@ -9,8 +9,8 @@ import scala.concurrent.{ExecutionContext, Future} * * @param directoriesConfig the directories config */ -class DirectoriesInitialization(directoriesConfig: ProjectDirectoriesConfig)(implicit - ec: ExecutionContext +class DirectoriesInitialization(directoriesConfig: ProjectDirectoriesConfig)( + implicit ec: ExecutionContext ) extends InitializationComponent with LazyLogging { diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/RepoInitialization.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/RepoInitialization.scala index 92ab5a939689..f0b1542e1b19 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/RepoInitialization.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/resource/RepoInitialization.scala @@ -23,10 +23,10 @@ import scala.util.{Failure, Success} * @param versionsRepo the versions repo */ class RepoInitialization( - directoriesConfig: ProjectDirectoriesConfig, - eventStream: EventStream, - suggestionsRepo: SqlSuggestionsRepo, - versionsRepo: SqlVersionsRepo + directoriesConfig: ProjectDirectoriesConfig, + eventStream: EventStream, + suggestionsRepo: SqlSuggestionsRepo, + versionsRepo: SqlVersionsRepo )(implicit ec: ExecutionContext) extends InitializationComponent with LazyLogging { diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala index 5c6f12f2ee04..faafdfeff777 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala @@ -272,11 +272,13 @@ class FileSystem extends FileSystemApi[BlockingIO] { Using.resource( Files.newInputStream(path.toPath, StandardOpenOption.READ) ) { stream => - val fileLength = Files.size(path.toPath) + val fileLength = Files.size(path.toPath) val lastByteIndex = fileLength - 1 - val lastSegIndex = segment.byteOffset + segment.length + val lastSegIndex = segment.byteOffset + segment.length - if (segment.byteOffset > lastByteIndex || lastSegIndex > lastByteIndex) { + if ( + segment.byteOffset > lastByteIndex || lastSegIndex > lastByteIndex + ) { throw FileSystem.ReadOutOfBounds(fileLength) } diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala index 0924c123bc98..06fef96b5ae9 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala @@ -160,26 +160,26 @@ trait FileSystemApi[F[_, _]] { ): F[FileSystemFailure, SHA3_224] /** Reads the bytes specified by `segment` from the specified `segment.file`. - * - * @param segment a description of the portion of a file to checksum - * @return either [[FileSystemFailure]] or the bytes representing the checksum - */ + * + * @param segment a description of the portion of a file to checksum + * @return either [[FileSystemFailure]] or the bytes representing the checksum + */ def readBytes(segment: FileSegment): F[FileSystemFailure, ReadBytesResult] } object FileSystemApi { /** A SHA3-224 digest on the filesystem. - * - * @param bytes the bytes that represent the value of the digest - */ + * + * @param bytes the bytes that represent the value of the digest + */ case class SHA3_224(bytes: Array[Byte]) /** The bytes read from the file. - * - * @param checksum the checksum of `bytes` - * @param bytes the bytes that were read - */ + * + * @param checksum the checksum of `bytes` + * @param bytes the bytes that were read + */ case class ReadBytesResult(checksum: SHA3_224, bytes: Array[Byte]) /** A representation of a segment in the file. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoDigestFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoDigestFactory.scala index 4ae0d35737d3..d828ad7fe5ef 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoDigestFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoDigestFactory.scala @@ -6,11 +6,11 @@ import org.enso.languageserver.protocol.binary.EnsoDigest object EnsoDigestFactory { /** Create a new EnsoDigest. - * - * @param bytes the bytes of the digest - * @param builder the flatbuffer builder in which the digest is created - * @return the offset of the digest in `builder` - */ + * + * @param bytes the bytes of the digest + * @param builder the flatbuffer builder in which the digest is created + * @return the offset of the digest in `builder` + */ def create(bytes: Array[Byte])(implicit builder: FlatBufferBuilder): Int = { val bytesOff = builder.createByteVector(bytes) EnsoDigest.createEnsoDigest(builder, bytesOff) diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ChecksumBytesHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ChecksumBytesHandler.scala index d26af9f0f35b..b69b6cb4e15b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ChecksumBytesHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ChecksumBytesHandler.scala @@ -130,10 +130,10 @@ object ChecksumBytesHandler { } /** Converts from a binary file segment to a protocol one. - * - * @param segment the segment to convert - * @return `segment` using protocol types - */ + * + * @param segment the segment to convert + * @return `segment` using protocol types + */ def convertFileSegment( segment: FileSegment ): FileManagerProtocol.Data.FileSegment = { diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBytesHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBytesHandler.scala index e9dc86392b77..815d9aa816d7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBytesHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBytesHandler.scala @@ -23,11 +23,11 @@ import org.enso.logger.masking.MaskedString import scala.concurrent.duration.FiniteDuration /** A handler for a read bytes request - * - * @param requestTimeout a request timeout - * @param fileManager a reference to the file-manager actor - * @param replyTo the actor to reply to - */ + * + * @param requestTimeout a request timeout + * @param fileManager a reference to the file-manager actor + * @param replyTo the actor to reply to + */ class ReadBytesHandler( requestTimeout: FiniteDuration, fileManager: ActorRef, diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/FileSegmentFactory.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/FileSegmentFactory.scala index 5c3fd869849b..22aaee888861 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/FileSegmentFactory.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/FileSegmentFactory.scala @@ -6,13 +6,13 @@ import org.enso.languageserver.protocol.binary.FileSegment object FileSegmentFactory { /** Create a new binary representation of a file segment. - * - * @param path the path to the file in which the segment exists - * @param byteOffset the start byte in the file (inclusive) - * @param segmentLength the number of bytes to read from `byteOffset` - * @param builder the flat buffers builder - * @return a new binary representation of a file segment - */ + * + * @param path the path to the file in which the segment exists + * @param byteOffset the start byte in the file (inclusive) + * @param segmentLength the number of bytes to read from `byteOffset` + * @param builder the flat buffers builder + * @return a new binary representation of a file segment + */ def create(path: Int, byteOffset: Long, segmentLength: Long)(implicit builder: FlatBufferBuilder ): Int = { diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/ReadBytesCommandFactory.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/ReadBytesCommandFactory.scala index d7102e7ec320..954206964c66 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/ReadBytesCommandFactory.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/ReadBytesCommandFactory.scala @@ -6,11 +6,11 @@ import org.enso.languageserver.protocol.binary.ReadBytesCommand object ReadBytesCommandFactory { /** Creates a ReadBytes command. - * - * @param fileSegment the file segment to read bytes from - * @param builder the flatbuffers builder - * @return the offset of the ReadBytesCommand - */ + * + * @param fileSegment the file segment to read bytes from + * @param builder the flatbuffers builder + * @return the offset of the ReadBytesCommand + */ def create(fileSegment: Int)(implicit builder: FlatBufferBuilder): Int = { ReadBytesCommand.createReadBytesCommand(builder, fileSegment) } diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala index 02238fac7ebd..3836d5586bf3 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala @@ -8,7 +8,10 @@ import org.graalvm.polyglot.{Context, PolyglotException} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class ModuleManagementTest extends AnyFlatSpec with Matchers with WithTemporaryDirectory { +class ModuleManagementTest + extends AnyFlatSpec + with Matchers + with WithTemporaryDirectory { var ctx: TestContext = _ override def beforeEach(): Unit = { @@ -18,7 +21,11 @@ class ModuleManagementTest extends AnyFlatSpec with Matchers with WithTemporaryD class TestContext(packageName: String) { val pkg: Package[File] = - PackageManager.Default.create(getTestDirectory.toFile, packageName, "Enso_Test") + PackageManager.Default.create( + getTestDirectory.toFile, + packageName, + "Enso_Test" + ) val executionContext = new PolyglotContext( Context .newBuilder(LanguageInfo.ID) @@ -100,58 +107,58 @@ class ModuleManagementTest extends AnyFlatSpec with Matchers with WithTemporaryD } it should "allow to create new, importable modules" in { - ctx.writeMain(""" - |import Enso_Test.Test.Foo - | - |main = Foo.foo + 1 - |""".stripMargin) - - ctx.writeFile( - "Foo.enso", - """ - |foo = 10 - |""".stripMargin - ) + ctx.writeMain(""" + |import Enso_Test.Test.Foo + | + |main = Foo.foo + 1 + |""".stripMargin) - val topScope = ctx.executionContext.getTopScope - topScope.registerModule( - "Enso_Test.Test.Foo", - ctx.mkFile("Foo.enso").getAbsolutePath - ) + ctx.writeFile( + "Foo.enso", + """ + |foo = 10 + |""".stripMargin + ) - val mainModule = topScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor - val mainFun = mainModule.getMethod(assocCons, "main").get - mainFun.execute(assocCons).asLong shouldEqual 11L + val topScope = ctx.executionContext.getTopScope + topScope.registerModule( + "Enso_Test.Test.Foo", + ctx.mkFile("Foo.enso").getAbsolutePath + ) + + val mainModule = topScope.getModule("Enso_Test.Test.Main") + val assocCons = mainModule.getAssociatedConstructor + val mainFun = mainModule.getMethod(assocCons, "main").get + mainFun.execute(assocCons).asLong shouldEqual 11L } it should "allow importing literal-source modules" in { - ctx.writeMain(""" - |import Enso_Test.Test.Foo - | - |main = Foo.foo + 1 - |""".stripMargin) - - ctx.writeFile( - "Foo.enso", - """ - |foo = 10 - |""".stripMargin - ) + ctx.writeMain(""" + |import Enso_Test.Test.Foo + | + |main = Foo.foo + 1 + |""".stripMargin) - val topScope = ctx.executionContext.getTopScope - val fooModule = topScope.registerModule( - "Enso_Test.Test.Foo", - ctx.mkFile("Foo.enso").getAbsolutePath - ) - fooModule.setSource(""" - |foo = 20 - |""".stripMargin) - - val mainModule = topScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor - val mainFun = mainModule.getMethod(assocCons, "main").get - mainFun.execute(assocCons).asLong shouldEqual 21L + ctx.writeFile( + "Foo.enso", + """ + |foo = 10 + |""".stripMargin + ) + + val topScope = ctx.executionContext.getTopScope + val fooModule = topScope.registerModule( + "Enso_Test.Test.Foo", + ctx.mkFile("Foo.enso").getAbsolutePath + ) + fooModule.setSource(""" + |foo = 20 + |""".stripMargin) + + val mainModule = topScope.getModule("Enso_Test.Test.Main") + val assocCons = mainModule.getAssociatedConstructor + val mainFun = mainModule.getMethod(assocCons, "main").get + mainFun.execute(assocCons).asLong shouldEqual 21L } it should "allow for module deletions" in { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/OptionsHelper.java b/engine/runtime/src/main/java/org/enso/interpreter/OptionsHelper.java index 13129a1b007b..d7f719dd4972 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/OptionsHelper.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/OptionsHelper.java @@ -24,8 +24,7 @@ public static Optional getProjectRoot(TruffleLanguage.Env env) { /** * Gets an optional override for the language home directory. * - * This is used mostly for the runtime tests, as language home is not normally - * defined there. + *

This is used mostly for the runtime tests, as language home is not normally defined there. */ public static Optional getLanguageHomeOverride(TruffleLanguage.Env env) { String option = env.getOptions().get(RuntimeOptions.LANGUAGE_HOME_OVERRIDE_KEY); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/epb/EpbLanguage.java b/engine/runtime/src/main/java/org/enso/interpreter/epb/EpbLanguage.java index 169405841ced..a57b599a463b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/epb/EpbLanguage.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/epb/EpbLanguage.java @@ -21,8 +21,8 @@ * is impossible to execute origin language's code when executing in the other context. Therefore * outer context values need to be specially wrapped before being passed (e.g. as arguments) to the * inner context, and inner context values need rewrapping for use in the outer context. See {@link - * org.enso.interpreter.epb.runtime.PolyglotProxy} and {@link - * ContextRewrapNode} for details of how and when this wrapping is done. + * org.enso.interpreter.epb.runtime.PolyglotProxy} and {@link ContextRewrapNode} for details of how + * and when this wrapping is done. * *

With the structure outlined above, EPB is the only language that is initialized in both inner * and outer contexts and thus it is very minimal. Its only role is to manage both contexts and diff --git a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapExceptionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapExceptionNode.java index ccadd7dc28aa..64ee8c1f288b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapExceptionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapExceptionNode.java @@ -14,7 +14,8 @@ @ReportPolymorphism public abstract class ContextRewrapExceptionNode extends Node { - /** Create a new context rewrap exception node. + /** + * Create a new context rewrap exception node. * * @return a new context rewrap exception node */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapNode.java b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapNode.java index 43b5e6c8fc04..7157b071fc51 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ContextRewrapNode.java @@ -15,7 +15,8 @@ @ReportPolymorphism public abstract class ContextRewrapNode extends Node { - /** Create a new context rewrap node. + /** + * Create a new context rewrap node. * * @return a new context rewrap node. */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ForeignEvalNode.java b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ForeignEvalNode.java index 44060121b6a3..4619b155a304 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ForeignEvalNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/epb/node/ForeignEvalNode.java @@ -33,7 +33,8 @@ public class ForeignEvalNode extends RootNode { * @param arguments argument names allowed in the function body * @return an instance of this node */ - public static ForeignEvalNode build(EpbLanguage language, EpbParser.Result code, List arguments) { + public static ForeignEvalNode build( + EpbLanguage language, EpbParser.Result code, List arguments) { return new ForeignEvalNode(language, code, arguments); } @@ -93,7 +94,8 @@ private void parseJs() { + "\n};poly_enso_eval"; Source source = Source.newBuilder(code.getLanguage().getTruffleId(), wrappedSrc, "").build(); - // After calling inner.enter, operating in a different, isolated truffle instance so need to call one with the correct semantics. + // After calling inner.enter, operating in a different, isolated truffle instance so need to + // call one with the correct semantics. CallTarget ct = EpbContext.get(this).getEnv().parsePublic(source); Object fn = rewrapNode.execute(ct.call(), inner, outer); foreign = insert(JsForeignNode.build(argNames.length, fn)); @@ -148,7 +150,8 @@ private void parseR() { String wrappedSrc = "function(" + args + "){\n" + code.getForeignSource() + "\n}"; Source source = Source.newBuilder(code.getLanguage().getTruffleId(), wrappedSrc, "").build(); - // After calling inner.enter, operating in a different, isolated truffle instance so need to call one with the correct semantics. + // After calling inner.enter, operating in a different, isolated truffle instance so need to + // call one with the correct semantics. CallTarget ct = EpbContext.get(this).getEnv().parsePublic(source); Object fn = rewrapNode.execute(ct.call(), inner, outer); foreign = insert(RForeignNodeGen.create(fn)); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/EnsoRootNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/EnsoRootNode.java index 3919fe4ccf5f..13a7be1dcfe0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/EnsoRootNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/EnsoRootNode.java @@ -128,5 +128,4 @@ protected boolean isInstrumentable() { public boolean isCloningAllowed() { return true; } - } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InteropConversionCallNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InteropConversionCallNode.java index ceaba73d1caf..b22947b493a2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InteropConversionCallNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InteropConversionCallNode.java @@ -44,7 +44,7 @@ InvokeConversionNode buildInvoker(int length) { return InvokeConversionNode.build( args, DefaultsExecutionMode.EXECUTE, ArgumentsExecutionMode.PRE_EXECUTED, 1); } - + Context getContext() { return Context.get(this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/InvokeFunctionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/InvokeFunctionNode.java index 8015fc3edcb8..c855673e25f5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/InvokeFunctionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/InvokeFunctionNode.java @@ -190,5 +190,4 @@ public SourceSection getSourceSection() { public void setId(UUID id) { functionCallInstrumentationNode.setId(id); } - } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java index 2b31d1f08695..dbf536e9620b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java @@ -11,7 +11,11 @@ public abstract class AnyResolverNode extends BaseResolverNode { public abstract Function execute(UnresolvedSymbol symbol, Object _this); @Specialization( - guards = {"!getContext().isInlineCachingDisabled()", "cachedSymbol == symbol", "function != null"}, + guards = { + "!getContext().isInlineCachingDisabled()", + "cachedSymbol == symbol", + "function != null" + }, limit = "CACHE_SIZE") Function resolveCached( UnresolvedSymbol symbol, @@ -22,8 +26,7 @@ Function resolveCached( } @Specialization(replaces = "resolveCached") - Function resolve( - UnresolvedSymbol symbol, Object _this) { + Function resolve(UnresolvedSymbol symbol, Object _this) { return throwIfNull(resolveMethodOnAny(symbol), _this, symbol); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java index 19568ba67d2b..d4d7dbfc3dbd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java @@ -26,9 +26,7 @@ Function resolveCached( } @Specialization(replaces = "resolveCached") - Function resolve( - UnresolvedSymbol symbol, - DataflowError _this) { + Function resolve(UnresolvedSymbol symbol, DataflowError _this) { return resolveMethodOnError(symbol); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/HostMethodCallNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/HostMethodCallNode.java index 6cb255fa090b..30336cbdaa9d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/HostMethodCallNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/HostMethodCallNode.java @@ -108,11 +108,18 @@ Object resolveHostMethod( "Impossible to reach here. The member is checked to be invocable."); } catch (ArityException e) { throw new PanicException( - Context.get(this).getBuiltins().error().makeArityError(e.getExpectedMinArity(), e.getExpectedMaxArity(), e.getActualArity()), + Context.get(this) + .getBuiltins() + .error() + .makeArityError(e.getExpectedMinArity(), e.getExpectedMaxArity(), e.getActualArity()), this); } catch (UnsupportedTypeException e) { throw new PanicException( - Context.get(this).getBuiltins().error().makeUnsupportedArgumentsError(e.getSuppliedValues()), this); + Context.get(this) + .getBuiltins() + .error() + .makeUnsupportedArgumentsError(e.getSuppliedValues()), + this); } } @@ -127,7 +134,8 @@ Object resolveHostField( @Cached BranchProfile errorProfile) { if (args.length != 0) { errorProfile.enter(); - throw new PanicException(Context.get(this).getBuiltins().error().makeArityError(0, 0, args.length), this); + throw new PanicException( + Context.get(this).getBuiltins().error().makeArityError(0, 0, args.length), this); } try { return hostValueToEnsoNode.execute(members.readMember(_this, symbol)); @@ -152,11 +160,18 @@ Object resolveHostConstructor( "Impossible to reach here. The member is checked to be instantiable."); } catch (ArityException e) { throw new PanicException( - Context.get(this).getBuiltins().error().makeArityError(e.getExpectedMinArity(), e.getExpectedMaxArity(), e.getActualArity()), + Context.get(this) + .getBuiltins() + .error() + .makeArityError(e.getExpectedMinArity(), e.getExpectedMaxArity(), e.getActualArity()), this); } catch (UnsupportedTypeException e) { throw new PanicException( - Context.get(this).getBuiltins().error().makeUnsupportedArgumentsError(e.getSuppliedValues()), this); + Context.get(this) + .getBuiltins() + .error() + .makeUnsupportedArgumentsError(e.getSuppliedValues()), + this); } } @@ -171,7 +186,8 @@ Object resolveHostArrayLength( @Cached HostValueToEnsoNode hostValueToEnsoNode) { if (args.length != 0) { errorProfile.enter(); - throw new PanicException(Context.get(this).getBuiltins().error().makeArityError(0, 0, args.length), this); + throw new PanicException( + Context.get(this).getBuiltins().error().makeArityError(0, 0, args.length), this); } try { return hostValueToEnsoNode.execute(arrays.getArraySize(_this)); @@ -192,7 +208,8 @@ Object resolveHostArrayRead( @Cached HostValueToEnsoNode hostValueToEnsoNode) { if (args.length != 1) { arityErrorProfile.enter(); - throw new PanicException(Context.get(this).getBuiltins().error().makeArityError(1, 1, args.length), this); + throw new PanicException( + Context.get(this).getBuiltins().error().makeArityError(1, 1, args.length), this); } if (!(args[0] instanceof Long)) { typeErrorProfile.enter(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java index 331bb15df7c4..b627577c543d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java @@ -19,10 +19,11 @@ public abstract class BooleanConstructorBranchNode extends BranchNode { private final AtomConstructor falseCons; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - BooleanConstructorBranchNode(AtomConstructor bool, - AtomConstructor trueAtom, - AtomConstructor falseAtom, - RootCallTarget branch) { + BooleanConstructorBranchNode( + AtomConstructor bool, + AtomConstructor trueAtom, + AtomConstructor falseAtom, + RootCallTarget branch) { super(branch); this.boolCons = bool; this.trueCons = trueAtom; @@ -37,11 +38,11 @@ public abstract class BooleanConstructorBranchNode extends BranchNode { * @return a node for matching in a case expression */ public static BooleanConstructorBranchNode build( - AtomConstructor bool, - AtomConstructor trueAtom, - AtomConstructor falseAtom, - RootCallTarget branch) { - return BooleanConstructorBranchNodeGen.create(bool,trueAtom, falseAtom, branch); + AtomConstructor bool, + AtomConstructor trueAtom, + AtomConstructor falseAtom, + RootCallTarget branch) { + return BooleanConstructorBranchNodeGen.create(bool, trueAtom, falseAtom, branch); } @Specialization diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java index 227b05b5bacc..fba6dc3edd4a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java @@ -93,11 +93,7 @@ public Object doMatch(VirtualFrame frame, Object object) { } CompilerDirectives.transferToInterpreter(); throw new PanicException( - Context.get(this) - .getBuiltins() - .error() - .makeInexhaustivePatternMatchError(object), - this); + Context.get(this).getBuiltins().error().makeInexhaustivePatternMatchError(object), this); } catch (BranchSelectedException e) { // Note [Branch Selection Control Flow] frame.setObject(getStateFrameSlot(), e.getResult().getState()); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java index 18d3ed9d0b67..578473838cb4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java @@ -40,10 +40,7 @@ void doConstructor(VirtualFrame frame, Object state, Atom target) { } @Specialization(guards = "isPolyglotObject(obj)") - void doLiteral( - VirtualFrame frame, - Object state, - Object obj) { + void doLiteral(VirtualFrame frame, Object state, Object obj) { if (polyglotProfile.profile(isPolyglotObject(obj))) { accept(frame, state, new Object[0]); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/InstantiateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/InstantiateNode.java index d51f2f51233d..629724cbe59e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/InstantiateNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/InstantiateNode.java @@ -74,8 +74,7 @@ public Object executeGeneric(VirtualFrame frame) { } else if (warningProfile.profile(argument instanceof WithWarnings)) { anyWarnings = true; WithWarnings originalArg = (WithWarnings) argument; - accumulatedWarnings = - accumulatedWarnings.append(originalArg.getReassignedWarnings(this)); + accumulatedWarnings = accumulatedWarnings.append(originalArg.getReassignedWarnings(this)); argumentValues[i] = originalArg.getValue(); } else if (TypesGen.isPanicSentinel(argument)) { sentinelProfile.enter(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java index d2c95b2d350a..3ecf88f24d37 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -2,9 +2,11 @@ import org.enso.interpreter.dsl.BuiltinType; -// Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` package along with True and False +// Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` package along with +// True and False // because it currently breaks a lot of code generation for builtin methods. // The name Boolean would clash with java.lang.Boolean. -// Before moving this definition to the `bool` package, as we should, one would have to address that problem first. +// Before moving this definition to the `bool` package, as we should, one would have to address that +// problem first. @BuiltinType public class Boolean extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index 7e9b55605a7e..dd5439e282d2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -1,8 +1,4 @@ package org.enso.interpreter.node.expression.builtin; -/** - * A base class for all classes annotated with @BuiltinType. - * Temporarily a placeholder. - */ -public abstract class Builtin { -} +/** A base class for all classes annotated with @BuiltinType. Temporarily a placeholder. */ +public abstract class Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index 7d7859a0a0c5..c0a2d610df90 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -9,35 +9,31 @@ import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; -@BuiltinMethod( - type = "Boolean", - name = "compare_to", - description = "Comparison for Booleans.") +@BuiltinMethod(type = "Boolean", name = "compare_to", description = "Comparison for Booleans.") public abstract class CompareToNode extends Node { - static CompareToNode build() { return CompareToNodeGen.create(); } + static CompareToNode build() { + return CompareToNodeGen.create(); + } - abstract Atom execute(Boolean _this, Object that); + abstract Atom execute(Boolean _this, Object that); - @Specialization - Atom doBoolean( - Boolean _this, - Boolean that) { - Ordering ordering = Context.get(this).getBuiltins().ordering(); - if (_this == that) { - return ordering.newEqual(); - } else if (_this) { - return ordering.newGreater(); - } else { - return ordering.newLess(); - } + @Specialization + Atom doBoolean(Boolean _this, Boolean that) { + Ordering ordering = Context.get(this).getBuiltins().ordering(); + if (_this == that) { + return ordering.newEqual(); + } else if (_this) { + return ordering.newGreater(); + } else { + return ordering.newLess(); } + } - @Specialization - Atom doOther( - Boolean _this, Object that) { - CompilerDirectives.transferToInterpreter(); - var bool = Context.get(this).getBuiltins().bool().newInstance(); - var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); - throw new PanicException(typeError, this); - } + @Specialization + Atom doOther(Boolean _this, Object that) { + CompilerDirectives.transferToInterpreter(); + var bool = Context.get(this).getBuiltins().bool().newInstance(); + var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); + throw new PanicException(typeError, this); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java index 97f137d994c2..0b551cabd1b0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java @@ -24,10 +24,7 @@ boolean doBoolean(boolean _this, boolean that) { @Specialization boolean doAtom( - Atom _this, - Atom that, - @Cached("getBooleanConstructor()") AtomConstructor boolCons - ) { + Atom _this, Atom that, @Cached("getBooleanConstructor()") AtomConstructor boolCons) { var thisCons = _this.getConstructor(); var thatCons = that.getConstructor(); return (thatCons == boolCons) && (thisCons == thatCons); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java index 749078772804..c0fbc7f57cfd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java @@ -26,8 +26,7 @@ static IfThenNode build() { abstract Stateful execute(@MonadicState Object state, boolean _this, @Suspend Object if_true); @Specialization - Stateful doExecute( - Object state, boolean _this, Object if_true) { + Stateful doExecute(Object state, boolean _this, Object if_true) { if (condProfile.profile(_this)) { return leftThunkExecutorNode.executeThunk(if_true, state, BaseNode.TailStatus.TAIL_DIRECT); } else { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java index 3bc7022157fe..a7aa5235d86f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java @@ -40,11 +40,7 @@ abstract Stateful execute( VirtualFrame frame, CallerInfo callerInfo, @MonadicState Object state, Object _this); @Specialization - Stateful doExecute( - VirtualFrame frame, - CallerInfo callerInfo, - Object state, - Object _this) { + Stateful doExecute(VirtualFrame frame, CallerInfo callerInfo, Object state, Object _this) { return new Stateful(state, Context.get(this).getNothing().newInstance()); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchAnyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchAnyNode.java index 62f4ee123fe7..2488a39e06fd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchAnyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchAnyNode.java @@ -29,8 +29,7 @@ public class CatchAnyNode extends Node { this.invokeCallableNode.setTailStatus(BaseNode.TailStatus.TAIL_DIRECT); } - Stateful execute( - VirtualFrame frame, @MonadicState Object state, Object _this, Object handler) { + Stateful execute(VirtualFrame frame, @MonadicState Object state, Object _this, Object handler) { return new Stateful(state, _this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index bae28014b5c8..03dd4939a4ed 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params="payload,internal_original_exception") +@BuiltinType(params = "payload,internal_original_exception") public class CaughtPanic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/GetAttachedStackTraceNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/GetAttachedStackTraceNode.java index 14faf75f40f1..f788cb6ce118 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/GetAttachedStackTraceNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/GetAttachedStackTraceNode.java @@ -19,7 +19,8 @@ Array execute(Object _this, @AcceptsError Object error) { return GetStackTraceNode.stackTraceToArray((Throwable) error); } else { Builtins builtins = Context.get(this).getBuiltins(); - throw new PanicException(builtins.error().makeTypeError("Throwable", error, "throwable"), this); + throw new PanicException( + builtins.error().makeTypeError("Throwable", error, "throwable"), this); } } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java index 2fa1c28c3312..ee9c449e2488 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -5,4 +5,3 @@ @BuiltinType(params = "scrutinee") public class InexhaustivePatternMatchError extends Builtin {} - diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java index b40ab5e91758..edca9f1e3508 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -5,4 +5,3 @@ @BuiltinType(params = "array,index") public class InvalidArrayIndexError extends Builtin {} - diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java index 8cc8cc2721ca..ae967c1f1881 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -5,4 +5,3 @@ @BuiltinType(params = "target") public class InvalidConversionTargetError extends Builtin {} - diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java index 43a6c92cfb1c..f10c4c4ece2a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -5,4 +5,3 @@ @BuiltinType(params = "name") public class ModuleDoesNotExist extends Builtin {} - diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/ArityErrorToDisplayTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/ArityErrorToDisplayTextNode.java index 6ad3564fa9e4..a371e60b1156 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/ArityErrorToDisplayTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/ArityErrorToDisplayTextNode.java @@ -21,10 +21,10 @@ Text doAtom(Atom _this) { Text expected = Text.create(String.valueOf(fields[0])); if (!fields[0].equals(fields[1])) { - expected = expected.add("-"); - if (!fields[1].equals(-1)) { - expected = expected.add(String.valueOf(fields[1])); - } + expected = expected.add("-"); + if (!fields[1].equals(-1)) { + expected = expected.add(String.valueOf(fields[1])); + } } return Text.create("Wrong number of arguments. Expected ") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/InvalidConversionTargetErrorToDisplayTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/InvalidConversionTargetErrorToDisplayTextNode.java index 73acf6aa1673..fb2c08445295 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/InvalidConversionTargetErrorToDisplayTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/displaytext/InvalidConversionTargetErrorToDisplayTextNode.java @@ -23,7 +23,7 @@ static InvalidConversionTargetErrorToDisplayTextNode build() { @Specialization Text doAtom( Atom _this, - @CachedLibrary(limit="10") InteropLibrary interopLibrary, + @CachedLibrary(limit = "10") InteropLibrary interopLibrary, @Cached TypeToDisplayTextNode fallback) { String fieldRep; Object target = _this.getFields()[0]; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/IsLanguageInstalledNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/IsLanguageInstalledNode.java index 13bea590c793..8e50683a284f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/IsLanguageInstalledNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/generic/IsLanguageInstalledNode.java @@ -20,10 +20,7 @@ static IsLanguageInstalledNode build() { } @Specialization - boolean doExecute( - Object _this, - Object language_name, - @Cached ExpectStringNode expectStringNode) { + boolean doExecute(Object _this, Object language_name, @Cached ExpectStringNode expectStringNode) { String name = expectStringNode.execute(language_name); return Context.get(this).getEnvironment().getPublicLanguages().get(name) != null; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/AddToClassPathNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/AddToClassPathNode.java index b095ef84f4db..e01475d6401c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/AddToClassPathNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/AddToClassPathNode.java @@ -20,10 +20,7 @@ static AddToClassPathNode build() { } @Specialization - Object doExecute( - Object _this, - Object path, - @Cached ExpectStringNode expectStringNode) { + Object doExecute(Object _this, Object path, @Cached ExpectStringNode expectStringNode) { Context context = Context.get(this); context .getEnvironment() diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/LookupClassNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/LookupClassNode.java index e8852e76ea27..9283fdecb1a6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/LookupClassNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/java/LookupClassNode.java @@ -15,9 +15,7 @@ static LookupClassNode build() { @Specialization Object doExecute( - Object _this, - Object name, - @Cached("build()") ExpectStringNode expectStringNode) { + Object _this, Object name, @Cached("build()") ExpectStringNode expectStringNode) { return Context.get(this).getEnvironment().lookupHostSymbol(expectStringNode.execute(name)); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java index f54ef59a57d8..8a9c23d06a6b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java @@ -58,9 +58,7 @@ Text doString(String txt) { } @Specialization(guards = {"o != null", "nulls.isNull(o)"}) - Atom doNull( - Object o, - @CachedLibrary(limit = "3") InteropLibrary nulls) { + Atom doNull(Object o, @CachedLibrary(limit = "3") InteropLibrary nulls) { return Context.get(this).getBuiltins().nothing().newInstance(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java index 9b801ecfc21c..be7d72e64080 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java @@ -23,11 +23,9 @@ static GetFileNode build() { @Specialization Object doGetFile( - Object _this, - Object path, - @Cached("build()") ExpectStringNode expectStringNode) { + Object _this, Object path, @Cached("build()") ExpectStringNode expectStringNode) { String pathStr = expectStringNode.execute(path); - var context= Context.get(this); + var context = Context.get(this); TruffleFile file = context.getEnvironment().getPublicTruffleFile(pathStr); EnsoFile ensoFile = new EnsoFile(file); return context.getEnvironment().asGuestValue(ensoFile); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java index 7d83195ea9f5..e06ed836f839 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -2,6 +2,6 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; + @BuiltinType(params = "prim_root_file,prim_config") -public class ProjectDescription extends Builtin { -} +public class ProjectDescription extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java index a0dec34d440e..9d23643bf847 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java @@ -35,11 +35,7 @@ Ordering getOrdering() { return Context.get(this).getBuiltins().ordering(); } - public int execute( - VirtualFrame frame, - Object comparator, - Object l, - Object r) { + public int execute(VirtualFrame frame, Object comparator, Object l, Object r) { Stateful result = invokeNode.execute(comparator, frame, EmptyMap.create(), new Object[] {l, r}); Object atom = result.getValue(); if (atom == getOrdering().less()) { @@ -52,7 +48,8 @@ public int execute( CompilerDirectives.transferToInterpreter(); var ordering = getOrdering().ordering(); throw new PanicException( - Context.get(this).getBuiltins().error().makeTypeError(ordering, atom, "comparator"), this); + Context.get(this).getBuiltins().error().makeTypeError(ordering, atom, "comparator"), + this); } } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java index 6110aae5903c..30a5309a7386 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java @@ -27,12 +27,7 @@ abstract Object execute( @Specialization Object doArray( - Object _this, - Array src, - long source_index, - Array dest, - long dest_index, - long count) { + Object _this, Array src, long source_index, Array dest, long dest_index, long count) { System.arraycopy( src.getItems(), (int) source_index, dest.getItems(), (int) dest_index, (int) count); return Context.get(this).getBuiltins().nothing().newInstance(); @@ -50,16 +45,20 @@ Object doPolyglotArray( @Cached HostValueToEnsoNode hostValueToEnsoNode) { try { for (int i = 0; i < count; i++) { - dest.getItems()[(int) dest_index + i] = hostValueToEnsoNode.execute( - arrays.readArrayElement(src, source_index + i)); + dest.getItems()[(int) dest_index + i] = + hostValueToEnsoNode.execute(arrays.readArrayElement(src, source_index + i)); } } catch (UnsupportedMessageException e) { throw new IllegalStateException("Unreachable"); } catch (InvalidArrayIndexException e) { throw new PanicException( - Context.get(this).getBuiltins().error().makeInvalidArrayIndexError(src, e.getInvalidIndex()), this); + Context.get(this) + .getBuiltins() + .error() + .makeInvalidArrayIndexError(src, e.getInvalidIndex()), + this); } - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing().newInstance(); } @Fallback diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/GetRefNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/GetRefNode.java index a4101ac10933..1f9a40de5157 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/GetRefNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/GetRefNode.java @@ -4,10 +4,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.data.Ref; -@BuiltinMethod( - type = "Ref", - name = "get", - description = "Gets the value stored in the reference.") +@BuiltinMethod(type = "Ref", name = "get", description = "Gets the value stored in the reference.") public class GetRefNode extends Node { Object execute(Object _this, Ref ref) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java index 8ff0c26e019e..d8349e9e2845 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java @@ -32,29 +32,20 @@ static SortNode build() { } @Specialization - Object doSortFunction( - VirtualFrame frame, - Array _this, - Function comparator) { + Object doSortFunction(VirtualFrame frame, Array _this, Function comparator) { Context context = Context.get(this); Comparator compare = getComparator(comparator, context); return runSort(compare, _this, context); } @Specialization - Object doSortCallable( - VirtualFrame frame, - Array _this, - Object comparator) { + Object doSortCallable(VirtualFrame frame, Array _this, Object comparator) { Comparator compare = (l, r) -> comparatorNode.execute(frame, comparator, l, r); return runSort(compare, _this, Context.get(this)); } @Specialization - Object doAtomThis( - VirtualFrame frame, - Atom _this, - Object that) { + Object doAtomThis(VirtualFrame frame, Atom _this, Object that) { return Context.get(this).getBuiltins().nothing().newInstance(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java index a25c5ead023f..86f820b79ea0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class BigInteger extends Builtin { -} +public class BigInteger extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java index a24d43a939df..72e05b732bd4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java @@ -1,7 +1,7 @@ package org.enso.interpreter.node.expression.builtin.number; + import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Decimal extends Builtin { -} +public class Decimal extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java index a06b6f0c4f60..67567d43a519 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Integer extends Builtin { -} +public class Integer extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java index a3acc2b12457..f96634396d75 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Number extends Builtin { -} +public class Number extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java index 4177e205c02c..b5c255042261 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class SmallInteger extends Builtin { -} +public class SmallInteger extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java index 0bdf652c3d96..8e36197eda35 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftNode.java @@ -16,7 +16,11 @@ import org.enso.interpreter.runtime.number.EnsoBigInteger; @ImportStatic(BigIntegerOps.class) -@BuiltinMethod(type = "Big_Integer", name = "bit_shift", description = "Bitwise shift.", aliases = "bit_shift_l") +@BuiltinMethod( + type = "Big_Integer", + name = "bit_shift", + description = "Bitwise shift.", + aliases = "bit_shift_l") public abstract class BitShiftNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); private final ConditionProfile fitsInIntProfileLeftShift = @@ -36,9 +40,7 @@ EnsoBigInteger doBigIntShiftLeft(EnsoBigInteger _this, long that) { } @Specialization(guards = "that >= 0", replaces = "doBigIntShiftLeft") - Object doBigIntShiftLeftExplicit( - EnsoBigInteger _this, - long that) { + Object doBigIntShiftLeftExplicit(EnsoBigInteger _this, long that) { if (fitsInIntProfileLeftShift.profile(BigIntegerOps.fitsInInt(that))) { return doBigIntShiftLeft(_this, that); } else { @@ -62,9 +64,7 @@ Object doBigIntShiftRightExplicit(EnsoBigInteger _this, long that) { } @Specialization - Object doBigIntThat( - EnsoBigInteger _this, - EnsoBigInteger that) { + Object doBigIntThat(EnsoBigInteger _this, EnsoBigInteger that) { if (!BigIntegerOps.nonNegative(that.getValue())) { return BigIntegerOps.nonNegative(_this.getValue()) ? 0L : -1L; } else { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java index 0e961f37977b..5df20d5aec26 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java @@ -28,9 +28,7 @@ Object doBigInteger( @Specialization Object doBigInteger( - EnsoBigInteger _this, - EnsoBigInteger that, - @Cached("build()") BitShiftNode bitShiftNode) { + EnsoBigInteger _this, EnsoBigInteger that, @Cached("build()") BitShiftNode bitShiftNode) { return bitShiftNode.execute(_this, new EnsoBigInteger(BigIntegerOps.negate(that.getValue()))); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java index 9f74b48aa127..e9f2669a2484 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java @@ -24,30 +24,22 @@ static CompareToNode build() { abstract Atom execute(EnsoBigInteger _this, Object that); @Specialization - Atom doLong( - EnsoBigInteger _this, - long that) { + Atom doLong(EnsoBigInteger _this, long that) { return getOrdering().fromJava(BigIntegerOps.compareTo(_this.getValue(), that)); } @Specialization - Atom doBigInt( - EnsoBigInteger _this, - EnsoBigInteger that) { + Atom doBigInt(EnsoBigInteger _this, EnsoBigInteger that) { return getOrdering().fromJava(BigIntegerOps.compareTo(_this.getValue(), that.getValue())); } @Specialization - Atom doDecimal( - EnsoBigInteger _this, - double that) { + Atom doDecimal(EnsoBigInteger _this, double that) { return getOrdering().fromJava(BigIntegerOps.compareTo(_this.getValue(), that)); } @Specialization - Atom doOther( - EnsoBigInteger _this, - Object that) { + Atom doOther(EnsoBigInteger _this, Object that) { CompilerDirectives.transferToInterpreter(); var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java index 0ae4b1eeb2ec..5d8bcfe50022 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java @@ -24,9 +24,7 @@ static DivNode build() { } @Specialization - Object doLong( - EnsoBigInteger _this, - long that) { + Object doLong(EnsoBigInteger _this, long that) { try { return toEnsoNumberNode.execute(BigIntegerOps.divide(_this.getValue(), that)); } catch (ArithmeticException e) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java index 3cc5746ea788..11dea8588b77 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java @@ -32,9 +32,7 @@ boolean doDouble(EnsoBigInteger _this, double that) { @Specialization boolean doAtom( - Atom _this, - Atom that, - @Cached("getBigIntegerConstructor()") AtomConstructor bigIntCons) { + Atom _this, Atom that, @Cached("getBigIntegerConstructor()") AtomConstructor bigIntCons) { var thisCons = _this.getConstructor(); var thatCons = that.getConstructor(); return (thatCons == bigIntCons) && (thisCons == thatCons); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java index cf6b357d712d..1a4ad3c8e382 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java @@ -24,9 +24,7 @@ static ModNode build() { } @Specialization - Object doLong( - EnsoBigInteger _this, - long that) { + Object doLong(EnsoBigInteger _this, long that) { try { return toEnsoNumberNode.execute(BigIntegerOps.modulo(_this.getValue(), that)); } catch (ArithmeticException e) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java index c0e89759f99b..b53ebe24f9e4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java @@ -21,9 +21,7 @@ static CompareToNode build() { abstract Atom execute(double _this, Object that); @Specialization - Atom doLong( - double _this, - long that) { + Atom doLong(double _this, long that) { if (_this == that) { return getOrdering().newEqual(); } else if (_this > that) { @@ -34,16 +32,12 @@ Atom doLong( } @Specialization - Atom doBigInt( - double _this, - EnsoBigInteger that) { + Atom doBigInt(double _this, EnsoBigInteger that) { return getOrdering().fromJava(BigIntegerOps.compareTo(_this, that.getValue())); } @Specialization - Atom doDecimal( - double _this, - double that) { + Atom doDecimal(double _this, double that) { if (_this == that) { return getOrdering().newEqual(); } else if (_this > that) { @@ -54,8 +48,7 @@ Atom doDecimal( } @Specialization - Atom doOther( - double _this, Object that) { + Atom doOther(double _this, Object that) { CompilerDirectives.transferToInterpreter(); var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java index e84a497ea2e8..f3d5bf1c5b6a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java @@ -36,9 +36,7 @@ boolean doBigInteger(double _this, EnsoBigInteger that) { @Specialization boolean doAtom( - Atom _this, - Atom that, - @Cached("getDecimalConstructor()") AtomConstructor decimalCons) { + Atom _this, Atom that, @Cached("getDecimalConstructor()") AtomConstructor decimalCons) { var thatCons = that.getConstructor(); var thisCons = _this.getConstructor(); return (thatCons == decimalCons) && (thisCons == thatCons); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java index a354f94ba88f..24e0d45d4de6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftNode.java @@ -16,7 +16,11 @@ import org.enso.interpreter.runtime.number.EnsoBigInteger; @ImportStatic(BigIntegerOps.class) -@BuiltinMethod(type = "Small_Integer", name = "bit_shift", description = "Bitwise shift.", aliases = "bit_shift_l") +@BuiltinMethod( + type = "Small_Integer", + name = "bit_shift", + description = "Bitwise shift.", + aliases = "bit_shift_l") public abstract class BitShiftNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); private final ConditionProfile canShiftLeftInLongProfile = @@ -38,8 +42,7 @@ long doLongShiftLeft(long _this, long that) { } @Specialization(guards = "that >= 0", replaces = "doLongShiftLeft") - Object doLongShiftLeftExplicit( - long _this, long that) { + Object doLongShiftLeftExplicit(long _this, long that) { if (canShiftLeftInLongProfile.profile(canShiftLeftInLong(_this, that))) { return doLongShiftLeft(_this, that); } else if (positiveFitsInInt.profile(BigIntegerOps.fitsInInt(that))) { @@ -69,9 +72,7 @@ long doLongShiftRightExplicit(long _this, long that) { } @Specialization - Object doBigInteger( - long _this, - EnsoBigInteger that) { + Object doBigInteger(long _this, EnsoBigInteger that) { if (!BigIntegerOps.nonNegative(that.getValue())) { return _this >= 0 ? 0L : -1L; } else { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java index 5944db2e40cd..1fb1d4a2ca07 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java @@ -24,9 +24,7 @@ static CompareToNode build() { abstract Atom execute(long _this, Object that); @Specialization - Atom doLong( - long _this, - long that) { + Atom doLong(long _this, long that) { if (_this == that) { return getOrdering().newEqual(); } else if (_this > that) { @@ -37,16 +35,12 @@ Atom doLong( } @Specialization - Atom doBigInt( - long _this, - EnsoBigInteger that) { + Atom doBigInt(long _this, EnsoBigInteger that) { return getOrdering().fromJava(BigIntegerOps.compareTo(_this, that.getValue())); } @Specialization - Atom doDecimal( - long _this, - double that) { + Atom doDecimal(long _this, double that) { if (_this == that) { return getOrdering().newEqual(); } else if (_this > that) { @@ -57,8 +51,7 @@ Atom doDecimal( } @Specialization - Atom doOther( - long _this, Object that) { + Atom doOther(long _this, Object that) { CompilerDirectives.transferToInterpreter(); var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java index af7056737c55..3f588a7622ed 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java @@ -30,9 +30,7 @@ boolean doDouble(long _this, double that) { @Specialization boolean doAtom( - Atom _this, - Atom that, - @Cached("getSmallIntegerConstructor()") AtomConstructor smallIntCons) { + Atom _this, Atom that, @Cached("getSmallIntegerConstructor()") AtomConstructor smallIntCons) { var thisCons = _this.getConstructor(); var thatCons = that.getConstructor(); return (thatCons == smallIntCons) && (thisCons == thatCons); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/utils/BigIntegerOps.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/utils/BigIntegerOps.java index b3b0a79d77ed..3d90644ed5cc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/utils/BigIntegerOps.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/utils/BigIntegerOps.java @@ -64,6 +64,7 @@ public static BigInteger subtract(BigInteger a, BigInteger b) { public static BigInteger divide(BigInteger a, long b) { return a.divide(BigInteger.valueOf(b)); } + @CompilerDirectives.TruffleBoundary public static BigInteger divide(BigInteger a, BigInteger b) { return a.divide(b); @@ -186,7 +187,7 @@ public static BigInteger bitShiftLeft(BigInteger a, int b) { @CompilerDirectives.TruffleBoundary public static BigInteger bitShiftRight(long a, int b) { - return BigIntegerOps.bitShiftRight(BigInteger.valueOf(a),b); + return BigIntegerOps.bitShiftRight(BigInteger.valueOf(a), b); } @CompilerDirectives.TruffleBoundary @@ -196,12 +197,12 @@ public static BigInteger bitShiftRight(BigInteger a, int b) { @CompilerDirectives.TruffleBoundary public static boolean nonNegative(BigInteger a) { - return BigIntegerOps.compare(a,BigInteger.ZERO) == 1; + return BigIntegerOps.compare(a, BigInteger.ZERO) == 1; } @CompilerDirectives.TruffleBoundary public static boolean isZero(BigInteger a) { - return BigIntegerOps.compare(a,BigInteger.ZERO) == 0; + return BigIntegerOps.compare(a, BigInteger.ZERO) == 0; } @CompilerDirectives.TruffleBoundary diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java index d5f018760849..5209451ae159 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java @@ -5,5 +5,4 @@ import org.enso.interpreter.dsl.BuiltinType; @BuiltinType -public class Equal extends Builtin { -} +public class Equal extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java index 3c86165121ef..a6fe2d5b277f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java @@ -1,8 +1,8 @@ package org.enso.interpreter.node.expression.builtin.ordering; + import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.dsl.BuiltinType; @BuiltinType -public class Greater extends Builtin { -} +public class Greater extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java index 31589bad3c0d..c502f085bd63 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java @@ -1,8 +1,8 @@ package org.enso.interpreter.node.expression.builtin.ordering; + import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.dsl.BuiltinType; @BuiltinType -public class Less extends Builtin { -} +public class Less extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java index 0d95814e0f6b..fb569d2939bd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java @@ -1,8 +1,8 @@ package org.enso.interpreter.node.expression.builtin.ordering; + import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.dsl.BuiltinType; @BuiltinType -public class Ordering extends Builtin { -} +public class Ordering extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java index 40fe2873f4e6..6ecd3af1d00c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class ManagedResource extends Builtin { -} +public class ManagedResource extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/RegisterNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/RegisterNode.java index a0b398bcef98..56465b5f028e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/RegisterNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/RegisterNode.java @@ -22,10 +22,7 @@ static RegisterNode build() { @Specialization @CompilerDirectives.TruffleBoundary - ManagedResource doRegister( - Object _this, - Object resource, - Function function) { + ManagedResource doRegister(Object _this, Object resource, Function function) { return Context.get(this).getResourceManager().register(resource, function); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/TakeNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/TakeNode.java index 23be672fe439..2c791295fea0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/TakeNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/TakeNode.java @@ -21,8 +21,7 @@ static TakeNode build() { abstract Object execute(Object _this, ManagedResource resource); @Specialization - Object doTake( - Object _this, ManagedResource resource) { + Object doTake(Object _this, ManagedResource resource) { Context.get(this).getResourceManager().take(resource); return resource.getResource(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/WithNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/WithNode.java index cfa4083dc378..f26d3ebb1080 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/WithNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/WithNode.java @@ -38,11 +38,7 @@ abstract Stateful execute( @Specialization Stateful doWith( - Object state, - VirtualFrame frame, - Object _this, - ManagedResource resource, - Object action) { + Object state, VirtualFrame frame, Object _this, ManagedResource resource, Object action) { ResourceManager resourceManager = Context.get(this).getResourceManager(); resourceManager.park(resource); try { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java index b296d997d081..49956ce693ee 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java @@ -44,10 +44,7 @@ Object doMultiCached( } @Specialization - Object doMultiUncached( - SmallMap state, - Object _this, - Object key) { + Object doMultiUncached(SmallMap state, Object _this, Object key) { int idx = state.indexOf(key); if (idx == SmallMap.NOT_FOUND) { return DataflowError.withoutTrace( @@ -58,15 +55,13 @@ Object doMultiUncached( } @Specialization - Object doEmpty( - EmptyMap state, Object _this, Object key) { + Object doEmpty(EmptyMap state, Object _this, Object key) { return DataflowError.withoutTrace( Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this); } @Specialization - Object doSingletonError( - SingletonMap state, Object _this, Object key) { + Object doSingletonError(SingletonMap state, Object _this, Object key) { return DataflowError.withoutTrace( Context.get(this).getBuiltins().error().makeUninitializedStateError(key), this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java index d1b5f6713635..b7de8a8366d4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/PutStateNode.java @@ -23,8 +23,7 @@ static PutStateNode build() { return PutStateNodeGen.create(); } - abstract Stateful execute( - @MonadicState Object state, Object _this, Object key, Object new_state); + abstract Stateful execute(@MonadicState Object state, Object _this, Object key, Object new_state); @Specialization(guards = "state.getKey() == key") Stateful doExistingSingleton(SingletonMap state, Object _this, Object key, Object new_state) { @@ -49,11 +48,7 @@ Stateful doExistingMultiCached( } @Specialization - Stateful doMultiUncached( - SmallMap state, - Object _this, - Object key, - Object new_state) { + Stateful doMultiUncached(SmallMap state, Object _this, Object key, Object new_state) { int index = state.indexOf(key); if (index == SmallMap.NOT_FOUND) { return new Stateful( @@ -66,11 +61,7 @@ Stateful doMultiUncached( } @Specialization - Stateful doError( - Object state, - Object _this, - Object key, - Object new_state) { + Stateful doError(Object state, Object _this, Object key, Object new_state) { return new Stateful( state, DataflowError.withoutTrace( diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java index ce65d0243deb..6ad561937f27 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java @@ -114,8 +114,7 @@ Object doCreate( Text returnOut = Text.create(out.toString()); Text returnErr = Text.create(err.toString()); - return ctx.getBuiltins() - .system().makeSystemResult(exitCode, returnOut, returnErr); + return ctx.getBuiltins().system().makeSystemResult(exitCode, returnOut, returnErr); } catch (IOException | InterruptedException e) { throw new PanicException(e.getMessage(), this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java index 1baba8e00b9a..599872cb26be 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = "exit_code,stdout,stderr") -public class SystemProcessResult extends Builtin { -} +public class SystemProcessResult extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/debug/EvalNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/debug/EvalNode.java index 4320fcf9cc05..9e426bf59fac 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/debug/EvalNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/debug/EvalNode.java @@ -75,13 +75,7 @@ RootCallTarget parseExpression(LocalScope scope, ModuleScope moduleScope, String expr = CaptureResultScopeNode.build(expr); } ClosureRootNode framedNode = - ClosureRootNode.build( - context.getLanguage(), - localScope, - moduleScope, - expr, - null, - ""); + ClosureRootNode.build(context.getLanguage(), localScope, moduleScope, expr, null, ""); return Truffle.getRuntime().createCallTarget(framedNode); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java index 8c00f5e76af3..4e40af56917e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java @@ -456,9 +456,10 @@ public TruffleLogger getLogger(Class klass) { return TruffleLogger.getLogger(LanguageInfo.ID, klass); } - /** Returns the current clock value and atomically increments the counter by one. + /** + * Returns the current clock value and atomically increments the counter by one. * - * The counter is used to track the creation time of warnings. + *

The counter is used to track the creation time of warnings. */ public long clockTick() { return clock.getAndIncrement(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java index 61afb076676d..8e509e3024ac 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java @@ -470,14 +470,16 @@ private static Object evalExpression( throws ArityException, UnsupportedTypeException { String expr = Types.extractArguments(args, String.class); Builtins builtins = context.getBuiltins(); - Function eval = builtins.getBuiltinFunction( - builtins.debug(), - Builtins.MethodNames.Debug.EVAL, - context.getLanguage()).orElseThrow(); + Function eval = + builtins + .getBuiltinFunction( + builtins.debug(), Builtins.MethodNames.Debug.EVAL, context.getLanguage()) + .orElseThrow(); CallerInfo callerInfo = new CallerInfo(null, LocalScope.root(), scope); Object state = context.getBuiltins().nothing().newInstance(); return callOptimiserNode - .executeDispatch(eval, callerInfo, state, new Object[] {builtins.debug(), Text.create(expr)}) + .executeDispatch( + eval, callerInfo, state, new Object[] {builtins.debug(), Text.create(expr)}) .getValue(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/ThreadManager.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/ThreadManager.java index ba0607a1db44..583019d7485e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/ThreadManager.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/ThreadManager.java @@ -69,15 +69,17 @@ public void interruptThreads() { interruptFlags.replaceAll((t, b) -> true); Object p = enter(); try { - env.submitThreadLocal(null, new ThreadLocalAction(true, false) { - @Override - protected void perform(ThreadLocalAction.Access access) { - Boolean interrupt = interruptFlags.get(access.getThread()); - if (Boolean.TRUE.equals(interrupt)) { - throw new ThreadInterruptedException(); - } - } - }); + env.submitThreadLocal( + null, + new ThreadLocalAction(true, false) { + @Override + protected void perform(ThreadLocalAction.Access access) { + Boolean interrupt = interruptFlags.get(access.getThread()); + if (Boolean.TRUE.equals(interrupt)) { + throw new ThreadInterruptedException(); + } + } + }); } finally { leave(p); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index a804bff474c4..3949e02eab45 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -50,13 +50,11 @@ public static class Debug { } } - private final Map>> builtinMethodNodes; + private final Map>> builtinMethodNodes; private final Map builtins; - @CompilerDirectives.CompilationFinal - private AtomConstructor debug; - @CompilerDirectives.CompilationFinal - private AtomConstructor projectDescription; + @CompilerDirectives.CompilationFinal private AtomConstructor debug; + @CompilerDirectives.CompilationFinal private AtomConstructor projectDescription; private final Error error; private final Module module; @@ -67,41 +65,29 @@ public static class Debug { private final Special special; // Builtin types - @CompilerDirectives.CompilationFinal - private AtomConstructor any; + @CompilerDirectives.CompilationFinal private AtomConstructor any; - @CompilerDirectives.CompilationFinal - private AtomConstructor nothing; + @CompilerDirectives.CompilationFinal private AtomConstructor nothing; - @CompilerDirectives.CompilationFinal - private AtomConstructor function; + @CompilerDirectives.CompilationFinal private AtomConstructor function; - @CompilerDirectives.CompilationFinal - private AtomConstructor polyglot; + @CompilerDirectives.CompilationFinal private AtomConstructor polyglot; - @CompilerDirectives.CompilationFinal - private AtomConstructor text; + @CompilerDirectives.CompilationFinal private AtomConstructor text; - @CompilerDirectives.CompilationFinal - private AtomConstructor array; + @CompilerDirectives.CompilationFinal private AtomConstructor array; - @CompilerDirectives.CompilationFinal - private AtomConstructor bool; + @CompilerDirectives.CompilationFinal private AtomConstructor bool; - @CompilerDirectives.CompilationFinal - private AtomConstructor trueConstructor; + @CompilerDirectives.CompilationFinal private AtomConstructor trueConstructor; - @CompilerDirectives.CompilationFinal - private AtomConstructor falseConstructor; + @CompilerDirectives.CompilationFinal private AtomConstructor falseConstructor; - @CompilerDirectives.CompilationFinal - private AtomConstructor dataflowError; + @CompilerDirectives.CompilationFinal private AtomConstructor dataflowError; - @CompilerDirectives.CompilationFinal - private AtomConstructor ref; + @CompilerDirectives.CompilationFinal private AtomConstructor ref; - @CompilerDirectives.CompilationFinal - private AtomConstructor managedResource; + @CompilerDirectives.CompilationFinal private AtomConstructor managedResource; /** * Creates an instance with builtin methods installed. @@ -126,31 +112,33 @@ public Builtins(Context context) { } /** - * Registers builtin methods with their corresponding Atom Constructor's owners. - * That way "special" builtin types have builtin methods in the scope without requiring - * everyone to always import full stdlib + * Registers builtin methods with their corresponding Atom Constructor's owners. That way + * "special" builtin types have builtin methods in the scope without requiring everyone to always + * import full stdlib * * @param builtins List of Builtin Types * @param scope Builtins scope * @param language The language the resulting function nodes should be associated with */ - private void registerBuiltinMethods(List builtins, ModuleScope scope, Language language) { - for (AtomConstructor atom: builtins) { + private void registerBuiltinMethods( + List builtins, ModuleScope scope, Language language) { + for (AtomConstructor atom : builtins) { String tpeName = atom.getName(); this.builtins.put(tpeName, atom); Map> methods = builtinMethodNodes.get(tpeName); if (methods != null) { - methods.forEach((methodName, clazz) -> { - Optional fun; - try { - Method meth = clazz.getMethod("makeFunction", Language.class); - fun = Optional.ofNullable((Function) meth.invoke(null, language)); - } catch (Exception e) { - e.printStackTrace(); - fun = Optional.empty(); - } - fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); - }); + methods.forEach( + (methodName, clazz) -> { + Optional fun; + try { + Method meth = clazz.getMethod("makeFunction", Language.class); + fun = Optional.ofNullable((Function) meth.invoke(null, language)); + } catch (Exception e) { + e.printStackTrace(); + fun = Optional.empty(); + } + fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); + }); } } } @@ -187,10 +175,10 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) /** * Returns a list of supported builtins. * - * Builtin types are marked via @BuiltinType annotation. THe metdata file represents a single - * builtin type per row. The format of the row is as follows: - * ::[,,...] - * where the last column gives a list of optional type's fields. + *

Builtin types are marked via @BuiltinType annotation. THe metdata file represents a single + * builtin type per row. The format of the row is as follows: ::[,,...] where the last column gives a + * list of optional type's fields. * * @param scope Builtins scope */ @@ -198,91 +186,112 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { - lines = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); + lines = + new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.toList()); } catch (Exception ioe) { lines = new ArrayList<>(); ioe.printStackTrace(); } - return lines.stream().map(line -> { - String[] builtinMeta = line.split(":"); - if (builtinMeta.length < 2 || builtinMeta.length > 3) { - throw new CompilerError("Invalid builtin metadata in: " + line + " " + builtinMeta.length); - } - - AtomConstructor builtin; - builtin = new AtomConstructor(builtinMeta[0], scope, true); - - if (builtinMeta.length == 2) { - builtin = builtin.initializeFields(); - } else { - // there are some type params - String[] paramNames = builtinMeta[2].split(","); - ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; - for (int i = 0; i < paramNames.length; i++) { - args[i] = new ArgumentDefinition(i, paramNames[i], ArgumentDefinition.ExecutionMode.EXECUTE); - } - builtin = builtin.initializeFields(args); - } - return builtin; - }).filter(b -> b != null).collect(Collectors.toList()); + return lines.stream() + .map( + line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length < 2 || builtinMeta.length > 3) { + throw new CompilerError( + "Invalid builtin metadata in: " + line + " " + builtinMeta.length); + } + + AtomConstructor builtin; + builtin = new AtomConstructor(builtinMeta[0], scope, true); + + if (builtinMeta.length == 2) { + builtin = builtin.initializeFields(); + } else { + // there are some type params + String[] paramNames = builtinMeta[2].split(","); + ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; + for (int i = 0; i < paramNames.length; i++) { + args[i] = + new ArgumentDefinition( + i, paramNames[i], ArgumentDefinition.ExecutionMode.EXECUTE); + } + builtin = builtin.initializeFields(args); + } + return builtin; + }) + .filter(b -> b != null) + .collect(Collectors.toList()); } /** * Returns a Map of builtin method nodes. * - * Builtin types are marked via @BuiltinMethod annotation. THe metdata file represents a single - * builtin method per row. The format of the row is as follows: - * : + *

Builtin types are marked via @BuiltinMethod annotation. THe metdata file represents a single + * builtin method per row. The format of the row is as follows: : * * @param scope Builtins scope * @return A map of builtin method nodes per builtin type name */ - private Map>> readBuiltinMethodsMetadata(ModuleScope scope) { + private Map>> readBuiltinMethodsMetadata( + ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(MethodDefinition.META_PATH)) { - lines = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); + lines = + new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.toList()); } catch (Exception ioe) { lines = new ArrayList<>(); ioe.printStackTrace(); } - Map>> methodNodes = new HashMap<>(); - - lines.forEach(line -> { - String[] builtinMeta = line.split(":"); - if (builtinMeta.length != 2) { - throw new CompilerError("Invalid builtin metadata in: " + line); - } - String[] builtinName = builtinMeta[0].split("\\."); - if (builtinName.length != 2) { - throw new CompilerError("Invalid builtin metadata in : " + line); - } - try { - Class clazz = (Class) Class.forName(builtinMeta[1]); - String builtinMethodOwner = builtinName[0]; - String builtinMethodName = builtinName[1]; - scope.getLocalConstructor(builtinMethodOwner).ifPresentOrElse(constr -> { - Map> atomNodes = methodNodes.get(builtinMethodOwner); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - methodNodes.put(constr.getName(), atomNodes); - } - atomNodes.put(builtinMethodName, clazz); - }, () -> { - Map> atomNodes = methodNodes.get(builtinMethodOwner); - if (atomNodes == null) { - atomNodes = new HashMap<>(); - // TODO: move away from String Map once Builtins are gone - methodNodes.put(builtinMethodOwner, atomNodes); - } - atomNodes.put(builtinMethodName, clazz); - }); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - }); + Map>> methodNodes = new HashMap<>(); + + lines.forEach( + line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length != 2) { + throw new CompilerError("Invalid builtin metadata in: " + line); + } + String[] builtinName = builtinMeta[0].split("\\."); + if (builtinName.length != 2) { + throw new CompilerError("Invalid builtin metadata in : " + line); + } + try { + Class clazz = (Class) Class.forName(builtinMeta[1]); + String builtinMethodOwner = builtinName[0]; + String builtinMethodName = builtinName[1]; + scope + .getLocalConstructor(builtinMethodOwner) + .ifPresentOrElse( + constr -> { + Map> atomNodes = + methodNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + methodNodes.put(constr.getName(), atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }, + () -> { + Map> atomNodes = + methodNodes.get(builtinMethodOwner); + if (atomNodes == null) { + atomNodes = new HashMap<>(); + // TODO: move away from String Map once Builtins are gone + methodNodes.put(builtinMethodOwner, atomNodes); + } + atomNodes.put(builtinMethodName, clazz); + }); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + }); return methodNodes; } @@ -292,17 +301,16 @@ private Map>> readBuiltinMethodsMetad * @param atom Atom Constructor owner of the function * @param methodName Name of the method * @param language The language the resulting function nodes should be associated with - * @return A non-empty function under the given name, if it exists. An empty value if no such builtin method was ever registerd + * @return A non-empty function under the given name, if it exists. An empty value if no such + * builtin method was ever registerd */ - - public Optional getBuiltinFunction(AtomConstructor atom, String methodName, Language language) { + public Optional getBuiltinFunction( + AtomConstructor atom, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone Map> atomNodes = builtinMethodNodes.get(atom.getName()); - if (atomNodes == null) - return Optional.empty(); + if (atomNodes == null) return Optional.empty(); Class clazz = atomNodes.get(methodName); - if (clazz == null) - return Optional.empty(); + if (clazz == null) return Optional.empty(); try { Method meth = clazz.getMethod("makeFunction", Language.class); return Optional.ofNullable((Function) meth.invoke(null, language)); @@ -355,7 +363,8 @@ public AtomConstructor text() { public AtomConstructor function() { if (function == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); - function = getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); + function = + getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); } return function; } @@ -405,7 +414,6 @@ private AtomConstructor managedResource() { return managedResource; } - /** @return the builtin Error types container. */ public Error error() { return error; @@ -425,8 +433,8 @@ public AtomConstructor any() { } /** - * Returns the {@code Debug} atom constructor. - * TODO: this is redundant, figure out a way to avoid createing spurious Debug builtin type + * Returns the {@code Debug} atom constructor. TODO: this is redundant, figure out a way to avoid + * createing spurious Debug builtin type * * @return the {@code Debug} atom constructor */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java index fc5e19f4b1d3..9cbcd47be810 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java @@ -4,5 +4,4 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class Debug extends Builtin { -} +public class Debug extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index b372fb5a5847..96ee794f5eac 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java @@ -13,65 +13,45 @@ /** Container for builtin Error types */ public class Error { - @CompilerDirectives.CompilationFinal - private AtomConstructor syntaxError; + @CompilerDirectives.CompilationFinal private AtomConstructor syntaxError; - @CompilerDirectives.CompilationFinal - private AtomConstructor typeError; + @CompilerDirectives.CompilationFinal private AtomConstructor typeError; - @CompilerDirectives.CompilationFinal - private AtomConstructor compileError; + @CompilerDirectives.CompilationFinal private AtomConstructor compileError; - @CompilerDirectives.CompilationFinal - private AtomConstructor inexhaustivePatternMatchError; + @CompilerDirectives.CompilationFinal private AtomConstructor inexhaustivePatternMatchError; - @CompilerDirectives.CompilationFinal - private AtomConstructor uninitializedState; + @CompilerDirectives.CompilationFinal private AtomConstructor uninitializedState; - @CompilerDirectives.CompilationFinal - private AtomConstructor noSuchMethodError; + @CompilerDirectives.CompilationFinal private AtomConstructor noSuchMethodError; - @CompilerDirectives.CompilationFinal - private AtomConstructor noSuchConversionError; + @CompilerDirectives.CompilationFinal private AtomConstructor noSuchConversionError; - @CompilerDirectives.CompilationFinal - private AtomConstructor polyglotError; + @CompilerDirectives.CompilationFinal private AtomConstructor polyglotError; - @CompilerDirectives.CompilationFinal - private AtomConstructor moduleNotInPackageError; + @CompilerDirectives.CompilationFinal private AtomConstructor moduleNotInPackageError; - @CompilerDirectives.CompilationFinal - private AtomConstructor arithmeticError; + @CompilerDirectives.CompilationFinal private AtomConstructor arithmeticError; - @CompilerDirectives.CompilationFinal - private AtomConstructor invalidArrayIndexError; + @CompilerDirectives.CompilationFinal private AtomConstructor invalidArrayIndexError; - @CompilerDirectives.CompilationFinal - private AtomConstructor arityError; + @CompilerDirectives.CompilationFinal private AtomConstructor arityError; - @CompilerDirectives.CompilationFinal - private AtomConstructor unsupportedArgumentsError; + @CompilerDirectives.CompilationFinal private AtomConstructor unsupportedArgumentsError; - @CompilerDirectives.CompilationFinal - private AtomConstructor moduleDoesNotExistError; + @CompilerDirectives.CompilationFinal private AtomConstructor moduleDoesNotExistError; - @CompilerDirectives.CompilationFinal - private AtomConstructor notInvokableError; + @CompilerDirectives.CompilationFinal private AtomConstructor notInvokableError; - @CompilerDirectives.CompilationFinal - private AtomConstructor invalidConversionTargetError; + @CompilerDirectives.CompilationFinal private AtomConstructor invalidConversionTargetError; - @CompilerDirectives.CompilationFinal - private AtomConstructor panic; + @CompilerDirectives.CompilationFinal private AtomConstructor panic; - @CompilerDirectives.CompilationFinal - private AtomConstructor caughtPanic; + @CompilerDirectives.CompilationFinal private AtomConstructor caughtPanic; - @CompilerDirectives.CompilationFinal - private Atom arithmeticErrorShiftTooBig; + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; - @CompilerDirectives.CompilationFinal - private Atom arithmeticErrorDivideByZero; + @CompilerDirectives.CompilationFinal private Atom arithmeticErrorDivideByZero; private static final Text shiftTooBigMessage = Text.create("Shift amount too large."); private static final Text divideByZeroMessage = Text.create("Cannot divide by zero."); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java index 8aa12582354d..e7a565077581 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java @@ -12,20 +12,15 @@ /** A container for all number-related builtins. */ public class Number { - @CompilerDirectives.CompilationFinal - private AtomConstructor smallInteger; + @CompilerDirectives.CompilationFinal private AtomConstructor smallInteger; - @CompilerDirectives.CompilationFinal - private AtomConstructor bigInteger; + @CompilerDirectives.CompilationFinal private AtomConstructor bigInteger; - @CompilerDirectives.CompilationFinal - private AtomConstructor integer; + @CompilerDirectives.CompilationFinal private AtomConstructor integer; - @CompilerDirectives.CompilationFinal - private AtomConstructor number; + @CompilerDirectives.CompilationFinal private AtomConstructor number; - @CompilerDirectives.CompilationFinal - private AtomConstructor decimal; + @CompilerDirectives.CompilationFinal private AtomConstructor decimal; private final Builtins builtins; @@ -70,7 +65,8 @@ public AtomConstructor getInteger() { public AtomConstructor getNumber() { if (number == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); - number = builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.number.Number.class); + number = + builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.number.Number.class); } return number; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java index eadff71a8b1e..6f9e6a5e5814 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java @@ -13,21 +13,15 @@ /** A container for builtin ordering types. */ public class Ordering { - @CompilerDirectives.CompilationFinal - private AtomConstructor ordering; + @CompilerDirectives.CompilationFinal private AtomConstructor ordering; - @CompilerDirectives.CompilationFinal - private AtomConstructor less; + @CompilerDirectives.CompilationFinal private AtomConstructor less; - @CompilerDirectives.CompilationFinal - private AtomConstructor equal; + @CompilerDirectives.CompilationFinal private AtomConstructor equal; - @CompilerDirectives.CompilationFinal - private AtomConstructor greater; - - @CompilerDirectives.CompilationFinal - private Builtins builtins; + @CompilerDirectives.CompilationFinal private AtomConstructor greater; + @CompilerDirectives.CompilationFinal private Builtins builtins; public Ordering(Builtins builtins) { this.builtins = builtins; @@ -68,7 +62,9 @@ public Atom newGreater() { public AtomConstructor ordering() { if (ordering == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); - ordering = builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); + ordering = + builtins.getBuiltinType( + org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); } return ordering; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java index 978e3f3f2612..241be8c9c371 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java @@ -54,7 +54,9 @@ public Function resolveFor(AtomConstructor into, AtomConstructor... constructors } @Override - public String toString() { return "UnresolvedConversion"; } + public String toString() { + return "UnresolvedConversion"; + } @ExportMessage String toDisplayString(boolean allowSideEffects) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java index c39a1c7e4752..0653d4bbb416 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java @@ -234,8 +234,7 @@ static Function resolveCached( } @Specialization(replaces = "resolveCached") - static Function resolve( - Atom _this, UnresolvedSymbol symbol) + static Function resolve(Atom _this, UnresolvedSymbol symbol) throws MethodDispatchLibrary.NoSuchMethodException { Function function = doResolve(_this.constructor, symbol); if (function == null) { @@ -257,9 +256,7 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function doResolve( - AtomConstructor cons, - AtomConstructor target, - UnresolvedConversion conversion) { + AtomConstructor cons, AtomConstructor target, UnresolvedConversion conversion) { return conversion.resolveFor(target, cons, getContext().getBuiltins().any()); } @@ -283,16 +280,12 @@ static Function resolveCached( @Cached("conversion") UnresolvedConversion cachedConversion, @Cached("_this.constructor") AtomConstructor cachedConstructor, @Cached("target") AtomConstructor cachedTarget, - @Cached("doResolve(cachedConstructor, cachedTarget, cachedConversion)") - Function function) { + @Cached("doResolve(cachedConstructor, cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve( - Atom _this, - AtomConstructor target, - UnresolvedConversion conversion) + static Function resolve(Atom _this, AtomConstructor target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(_this.constructor, target, conversion); if (function == null) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index c176330f582a..dc6e3591bf8c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -44,7 +44,8 @@ public final class AtomConstructor implements TruffleObject { /** * Creates a new Atom constructor for a given name. The constructor is not valid until {@link - * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} is called. + * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} + * is called. * * @param name the name of the Atom constructor * @param definitionScope the scope in which this constructor was defined @@ -55,7 +56,8 @@ public AtomConstructor(String name, ModuleScope definitionScope) { /** * Creates a new Atom constructor for a given name. The constructor is not valid until {@link - * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} is called. + * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} + * is called. * * @param name the name of the Atom constructor * @param definitionScope the scope in which this constructor was defined @@ -78,26 +80,28 @@ public boolean isBuiltin() { public void setShadowDefinitions(ModuleScope scope) { if (builtin) { // Ensure that synthetic methods, such as getters for fields are in the scope - // Some scopes won't have any methods at this point, e.g., Nil or Nothing, hence the null check. - Map methods = this.definitionScope.getMethods().get(this); + // Some scopes won't have any methods at this point, e.g., Nil or Nothing, hence the null + // check. + Map methods = this.definitionScope.getMethods().get(this); if (methods != null) { methods.forEach((name, fun) -> scope.registerMethod(this, name, fun)); } this.definitionScope = scope; } else { - throw new RuntimeException("Attempting to modify scope of a non-builtin type post-construction is not allowed"); + throw new RuntimeException( + "Attempting to modify scope of a non-builtin type post-construction is not allowed"); } } /** - * Generates a constructor function for this {@link AtomConstructor}. - * Note that such manually constructed argument definitions must not have default arguments. + * Generates a constructor function for this {@link AtomConstructor}. Note that such manually + * constructed argument definitions must not have default arguments. * * @return {@code this}, for convenience */ public AtomConstructor initializeFields(ArgumentDefinition... args) { ExpressionNode[] reads = new ExpressionNode[args.length]; - for (int i=0; i ensureConversionsFor(AtomConstructor cons) { + private Map ensureConversionsFor(AtomConstructor cons) { return conversions.computeIfAbsent(cons, k -> new HashMap<>()); } @@ -143,7 +143,6 @@ private Map getConversionsFor(AtomConstructor cons) { return result; } - /** * Registers a conversion method for a given type * @@ -151,7 +150,8 @@ private Map getConversionsFor(AtomConstructor cons) { * @param fromType type the conversion was defined from * @param function the {@link Function} associated with this definition */ - public void registerConversionMethod(AtomConstructor toType, AtomConstructor fromType, Function function) { + public void registerConversionMethod( + AtomConstructor toType, AtomConstructor fromType, Function function) { Map sourceMap = ensureConversionsFor(toType); if (sourceMap.containsKey(fromType)) { throw new RedefinedConversionException(toType.getName(), fromType.getName()); @@ -207,7 +207,8 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { if (atom.isBuiltin()) { // Unfortunately locally defined extensions get associated with the module rather than a type // within a module. - // BindingsMap would need to be enhanced to resolve to the constructor rather than a module but + // BindingsMap would need to be enhanced to resolve to the constructor rather than a module + // but // that will likely break some use-cases as it could become ambiguous. AtomConstructor moduleTypeInStdLib = atom.getDefinitionScope().associatedType; definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); @@ -233,11 +234,10 @@ public Function lookupConversionDefinition(AtomConstructor atom, AtomConstructor return definedHere; } return imports.stream() - .map(scope -> scope.getExportedConversion(atom, target)) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); - + .map(scope -> scope.getExportedConversion(atom, target)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } private Function getExportedMethod(AtomConstructor atom, String name) { @@ -258,10 +258,10 @@ private Function getExportedConversion(AtomConstructor atom, AtomConstructor tar return here; } return exports.stream() - .map(scope -> scope.getConversionsFor(target).get(atom)) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); + .map(scope -> scope.getConversionsFor(target).get(atom)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } /** 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 307dc816a089..72744005450c 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 @@ -110,9 +110,7 @@ Array getMembers(boolean includeInternal) { /** Handles member invocation through the polyglot API. */ @ExportMessage abstract static class InvokeMember { - private static Module getModule( - TopLevelScope scope, - Object[] arguments) + private static Module getModule(TopLevelScope scope, Object[] arguments) throws ArityException, UnsupportedTypeException, UnknownIdentifierException { String moduleName = Types.extractArguments(arguments, String.class); @@ -161,10 +159,7 @@ private static Object compile(Object[] arguments, Context context) } @Specialization - static Object doInvoke( - TopLevelScope scope, - String member, - Object[] arguments) + static Object doInvoke(TopLevelScope scope, String member, Object[] arguments) throws UnknownIdentifierException, ArityException, UnsupportedTypeException { switch (member) { case MethodNames.TopScope.GET_MODULE: diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala index b45232b0d21a..601c53d82ea6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala @@ -431,7 +431,7 @@ object AstView { .Right(AST.Ident.Opr("~"), AST.Ident.Var.any(v)) => Some((v, expr, None, true)) case AST.App.Section - .Right(AST.Ident.Opr("~"), AST.Ident.Blank.any(v)) => + .Right(AST.Ident.Opr("~"), AST.Ident.Blank.any(v)) => Some((v, expr, None, true)) case _ => None } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 4f09bedfc563..f088fe4a42f9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -10,28 +10,68 @@ import org.enso.compiler.data.{BindingsMap, CompilerConfig} import org.enso.compiler.exception.{BadPatternMatch, CompilerError} import org.enso.compiler.pass.analyse.AliasAnalysis.Graph.{Scope => AliasScope} import org.enso.compiler.pass.analyse.AliasAnalysis.{Graph => AliasGraph} -import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis, DataflowAnalysis, TailCall} +import org.enso.compiler.pass.analyse.{ + AliasAnalysis, + BindingAnalysis, + DataflowAnalysis, + TailCall +} import org.enso.compiler.pass.optimise.ApplicationSaturation -import org.enso.compiler.pass.resolve.{ExpressionAnnotations, MethodDefinitions, Patterns, UppercaseNames} +import org.enso.compiler.pass.resolve.{ + ExpressionAnnotations, + MethodDefinitions, + Patterns, + UppercaseNames +} import org.enso.interpreter.epb.EpbParser import org.enso.interpreter.node.callable.argument.ReadArgumentNode -import org.enso.interpreter.node.callable.function.{BlockNode, CreateFunctionNode} +import org.enso.interpreter.node.callable.function.{ + BlockNode, + CreateFunctionNode +} import org.enso.interpreter.node.callable.thunk.{CreateThunkNode, ForceNode} -import org.enso.interpreter.node.callable.{ApplicationNode, InvokeCallableNode, SequenceLiteralNode} +import org.enso.interpreter.node.callable.{ + ApplicationNode, + InvokeCallableNode, + SequenceLiteralNode +} import org.enso.interpreter.node.controlflow.caseexpr._ import org.enso.interpreter.node.expression.atom.QualifiedAccessorNode import org.enso.interpreter.node.expression.constant._ import org.enso.interpreter.node.expression.foreign.ForeignMethodCallNode -import org.enso.interpreter.node.expression.literal.{BigIntegerLiteralNode, DecimalLiteralNode, IntegerLiteralNode, TextLiteralNode} +import org.enso.interpreter.node.expression.literal.{ + BigIntegerLiteralNode, + DecimalLiteralNode, + IntegerLiteralNode, + TextLiteralNode +} import org.enso.interpreter.node.scope.{AssignmentNode, ReadLocalVariableNode} -import org.enso.interpreter.node.{BaseNode, ClosureRootNode, MethodRootNode, ExpressionNode => RuntimeExpression} +import org.enso.interpreter.node.{ + BaseNode, + ClosureRootNode, + MethodRootNode, + ExpressionNode => RuntimeExpression +} import org.enso.interpreter.runtime.Context -import org.enso.interpreter.runtime.callable.{UnresolvedConversion, UnresolvedSymbol} -import org.enso.interpreter.runtime.callable.argument.{ArgumentDefinition, CallArgument} +import org.enso.interpreter.runtime.callable.{ + UnresolvedConversion, + UnresolvedSymbol +} +import org.enso.interpreter.runtime.callable.argument.{ + ArgumentDefinition, + CallArgument +} import org.enso.interpreter.runtime.callable.atom.AtomConstructor -import org.enso.interpreter.runtime.callable.function.{FunctionSchema, Function => RuntimeFunction} +import org.enso.interpreter.runtime.callable.function.{ + FunctionSchema, + Function => RuntimeFunction +} import org.enso.interpreter.runtime.data.text.Text -import org.enso.interpreter.runtime.scope.{FramePointer, LocalScope, ModuleScope} +import org.enso.interpreter.runtime.scope.{ + FramePointer, + LocalScope, + ModuleScope +} import org.enso.interpreter.{Constants, Language} import java.math.BigInteger @@ -42,24 +82,24 @@ import scala.collection.mutable.ArrayBuffer import scala.jdk.OptionConverters._ /** This is an implementation of a codegeneration pass that lowers the Enso - * [[IR]] into the truffle [[org.enso.compiler.core.Core.Node]] structures that - * are actually executed. - * - * It should be noted that, as is, there is no support for cross-module links, - * with each lowering pass operating solely on a single module. - * - * @param context the language context instance for which this is executing - * @param source the source code that corresponds to the text for which code - * is being generated - * @param moduleScope the scope of the module for which code is being generated - * @param compilerConfig the configuration for the compiler - */ + * [[IR]] into the truffle [[org.enso.compiler.core.Core.Node]] structures that + * are actually executed. + * + * It should be noted that, as is, there is no support for cross-module links, + * with each lowering pass operating solely on a single module. + * + * @param context the language context instance for which this is executing + * @param source the source code that corresponds to the text for which code + * is being generated + * @param moduleScope the scope of the module for which code is being generated + * @param compilerConfig the configuration for the compiler + */ class IrToTruffle( - val context: Context, - val source: Source, - val moduleScope: ModuleScope, - val compilerConfig: CompilerConfig - ) { + val context: Context, + val source: Source, + val moduleScope: ModuleScope, + val compilerConfig: CompilerConfig +) { val language: Language = context.getLanguage @@ -68,31 +108,31 @@ class IrToTruffle( // ========================================================================== /** Executes the codegen pass on the input [[IR]]. - * - * Please note that the IR passed to this function should not contain _any_ - * errors (members of [[IR.Error]]). These must be dealt with and reported - * before codegen runs, as they will cause a compiler error. - * - * In future, this restriction will be relaxed to admit errors that are - * members of [[IR.Diagnostic.Kind.Interactive]], such that we can display - * these to users during interactive execution. - * - * @param ir the IR to generate code for - */ + * + * Please note that the IR passed to this function should not contain _any_ + * errors (members of [[IR.Error]]). These must be dealt with and reported + * before codegen runs, as they will cause a compiler error. + * + * In future, this restriction will be relaxed to admit errors that are + * members of [[IR.Diagnostic.Kind.Interactive]], such that we can display + * these to users during interactive execution. + * + * @param ir the IR to generate code for + */ def run(ir: IR.Module): Unit = processModule(ir) /** Executes the codegen pass on an inline input. - * - * @param ir the IR to generate code for - * @param localScope the scope in which the inline input exists - * @param scopeName the name of `localScope` - * @return an truffle expression representing `ir` - */ + * + * @param ir the IR to generate code for + * @param localScope the scope in which the inline input exists + * @param scopeName the name of `localScope` + * @return an truffle expression representing `ir` + */ def runInline( - ir: IR.Expression, - localScope: LocalScope, - scopeName: String - ): RuntimeExpression = { + ir: IR.Expression, + localScope: LocalScope, + scopeName: String + ): RuntimeExpression = { new ExpressionProcessor(localScope, scopeName).runInline(ir) } @@ -101,13 +141,13 @@ class IrToTruffle( // ========================================================================== /** Generates truffle nodes from the top-level definitions of an Enso module - * and registers these definitions in scope in the compiler. - * - * It does not directly return any constructs, but instead registers these - * constructs for later access in the compiler and language context. - * - * @param module the module for which code should be generated - */ + * and registers these definitions in scope in the compiler. + * + * It does not directly return any constructs, but instead registers these + * constructs for later access in the compiler and language context. + * + * @param module the module for which code should be generated + */ private def processModule(module: IR.Module): Unit = { generateMethods() generateReExportBindings(module) @@ -130,7 +170,7 @@ class IrToTruffle( // Register the imports in scope imports.foreach { - case poly@Import.Polyglot(i: Import.Polyglot.Java, _, _, _, _) => + case poly @ Import.Polyglot(i: Import.Polyglot.Java, _, _, _, _) => this.moduleScope.registerPolyglotSymbol( poly.getVisibleName, context.getEnvironment.lookupHostSymbol(i.getJavaName) @@ -173,28 +213,35 @@ class IrToTruffle( ) val argDefs = new Array[ArgumentDefinition](atomDefn.arguments.size) - val argumentExpressions = new ArrayBuffer[(RuntimeExpression, RuntimeExpression)] + val argumentExpressions = + new ArrayBuffer[(RuntimeExpression, RuntimeExpression)] for (idx <- atomDefn.arguments.indices) { val unprocessedArg = atomDefn.arguments(idx) - val arg = argFactory.run(unprocessedArg, idx) + val arg = argFactory.run(unprocessedArg, idx) val occInfo = unprocessedArg - .unsafeGetMetadata( - AliasAnalysis, - "No occurrence on an argument definition." - ) - .unsafeAs[AliasAnalysis.Info.Occurrence] + .unsafeGetMetadata( + AliasAnalysis, + "No occurrence on an argument definition." + ) + .unsafeAs[AliasAnalysis.Info.Occurrence] val slot = localScope.createVarSlot(occInfo.id) argDefs(idx) = arg - val readArg = ReadArgumentNode.build(idx, arg.getDefaultValue.orElse(null)) + val readArg = + ReadArgumentNode.build(idx, arg.getDefaultValue.orElse(null)) val assignmentArg = AssignmentNode.build(readArg, slot) - val argRead = ReadLocalVariableNode.build(new FramePointer(0, slot)) + val argRead = ReadLocalVariableNode.build(new FramePointer(0, slot)) argumentExpressions.append((assignmentArg, argRead)) } val (assignments, reads) = argumentExpressions.unzip if (!atomCons.isInitialized) { - atomCons.initializeFields(localScope, assignments.toArray, reads.toArray, argDefs: _*) + atomCons.initializeFields( + localScope, + assignments.toArray, + reads.toArray, + argDefs: _* + ) } } @@ -204,7 +251,7 @@ class IrToTruffle( .unsafeGetMetadata( AliasAnalysis, s"Missing scope information for method " + - s"`${methodDef.typeName.name}.${methodDef.methodName.name}`." + s"`${methodDef.typeName.name}.${methodDef.methodName.name}`." ) .unsafeAs[AliasAnalysis.Info.Scope.Root] val dataflowInfo = methodDef.unsafeGetMetadata( @@ -246,15 +293,24 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => - val builtinFunction = context.getBuiltins.getBuiltinFunction(cons, methodDef.methodName.name, language) - builtinFunction - .toScala + val builtinFunction = context.getBuiltins + .getBuiltinFunction(cons, methodDef.methodName.name, language) + builtinFunction.toScala .map(Some(_)) - .toRight(new CompilerError(s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}")) - .left.flatMap( l => + .toRight( + new CompilerError( + s"Unable to find Truffle Node for method ${cons.getName()}.${methodDef.methodName.name}" + ) + ) + .left + .flatMap(l => // Builtin Types Number and Integer have methods only for documentation purposes - if (cons == context.getBuiltins.number().getNumber || - cons == context.getBuiltins.number().getInteger) Right(None) else Left(l)) + if ( + cons == context.getBuiltins.number().getNumber || + cons == context.getBuiltins.number().getInteger + ) Right(None) + else Left(l) + ) case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) @@ -268,15 +324,21 @@ class IrToTruffle( methodDef.methodName.name ) val callTarget = Truffle.getRuntime.createCallTarget(rootNode) - Right(Some(new RuntimeFunction( - callTarget, - null, - new FunctionSchema(arguments: _*) - ))) + Right( + Some( + new RuntimeFunction( + callTarget, + null, + new FunctionSchema(arguments: _*) + ) + ) + ) case _ => - Left(new CompilerError( - "Method bodies must be functions at the point of codegen." - )) + Left( + new CompilerError( + "Method bodies must be functions at the point of codegen." + ) + ) } function match { case Left(failure) => @@ -284,7 +346,7 @@ class IrToTruffle( case Right(Some(fun)) => moduleScope.registerMethod(cons, methodDef.methodName.name, fun) case _ => - // Don't register dummy function nodes + // Don't register dummy function nodes } } }) @@ -300,7 +362,7 @@ class IrToTruffle( .unsafeGetMetadata( AliasAnalysis, s"Missing scope information for conversion " + - s"`${methodDef.typeName.name}.${methodDef.methodName.name}`." + s"`${methodDef.typeName.name}.${methodDef.methodName.name}`." ) .unsafeAs[AliasAnalysis.Info.Scope.Root] val dataflowInfo = methodDef.unsafeGetMetadata( @@ -308,7 +370,8 @@ class IrToTruffle( "Method definition missing dataflow information." ) - val toOpt = getConstructorResolution(methodDef.methodReference.typePointer) + val toOpt = + getConstructorResolution(methodDef.methodReference.typePointer) val fromOpt = getConstructorResolution(methodDef.sourceTypeName) toOpt.zip(fromOpt).foreach { case (toType, fromType) => val expressionProcessor = new ExpressionProcessor( @@ -359,17 +422,19 @@ class IrToTruffle( private def isBuiltinMethod(expression: IR.Expression): Boolean = { expression .getMetadata(ExpressionAnnotations) - .exists(_.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName)) + .exists( + _.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName) + ) } /** Creates a source section from a given location in the code. - * - * @param location the location to turn into a section - * @return the source section corresponding to `location` - */ + * + * @param location the location to turn into a section + * @return the source section corresponding to `location` + */ private def makeSection( - location: Option[IdentifiedLocation] - ): SourceSection = { + location: Option[IdentifiedLocation] + ): SourceSection = { location .map(loc => source.createSection(loc.start, loc.length)) .getOrElse(source.createUnavailableSection()) @@ -398,8 +463,8 @@ class IrToTruffle( } private def getTailStatus( - expression: IR.Expression - ): BaseNode.TailStatus = { + expression: IR.Expression + ): BaseNode.TailStatus = { val isTailPosition = expression.getMetadata(TailCall).contains(TailCall.TailPosition.Tail) val isTailAnnotated = TailCall.isTailAnnotated(expression) @@ -415,17 +480,17 @@ class IrToTruffle( } /** Sets the source section for a given expression node to the provided - * location. - * - * @param expr the expression to set the location for - * @param location the location to assign to `expr` - * @tparam T the type of `expr` - * @return `expr` with its location set to `location` - */ + * location. + * + * @param expr the expression to set the location for + * @param location the location to assign to `expr` + * @tparam T the type of `expr` + * @return `expr` with its location set to `location` + */ private def setLocation[T <: RuntimeExpression]( - expr: T, - location: Option[IdentifiedLocation] - ): T = { + expr: T, + location: Option[IdentifiedLocation] + ): T = { location.foreach { loc => expr.setSourceLocation(loc.start, loc.length) loc.id.foreach { id => expr.setId(id) } @@ -439,7 +504,7 @@ class IrToTruffle( private def generateEnsoProjectMethod(): Unit = { val name = BindingsMap.Generated.ensoProjectMethodName - val pkg = context.getPackageOf(moduleScope.getModule.getSourceFile) + val pkg = context.getPackageOf(moduleScope.getModule.getSourceFile) val body = Truffle.getRuntime.createCallTarget( new EnsoProjectNode(language, context, pkg) ) @@ -522,31 +587,31 @@ class IrToTruffle( // ========================================================================== /** This class is responsible for performing codegen of [[IR]] constructs that - * are Enso program expressions. - * - * @param scope the scope in which the code generation is occurring - * @param scopeName the name of `scope` - */ + * are Enso program expressions. + * + * @param scope the scope in which the code generation is occurring + * @param scopeName the name of `scope` + */ sealed private class ExpressionProcessor( - val scope: LocalScope, - val scopeName: String - ) { + val scope: LocalScope, + val scopeName: String + ) { private var currentVarName = "" // === Construction ======================================================= /** Constructs an [[ExpressionProcessor]] instance with a defaulted local - * scope. - * - * @param scopeName the name to attribute to the default local scope. - */ + * scope. + * + * @param scopeName the name to attribute to the default local scope. + */ def this( - scopeName: String, - graph: AliasGraph, - scope: AliasScope, - dataflowInfo: DataflowAnalysis.Metadata - ) = { + scopeName: String, + graph: AliasGraph, + scope: AliasScope, + dataflowInfo: DataflowAnalysis.Metadata + ) = { this( new LocalScope(None, graph, scope, dataflowInfo), scopeName @@ -554,35 +619,35 @@ class IrToTruffle( } /** Creates an instance of [[ExpressionProcessor]] that operates in a child - * scope of `this`. - * - * @param name the name of the child scope - * @return an expression processor operating on a child scope - */ + * scope of `this`. + * + * @param name the name of the child scope + * @return an expression processor operating on a child scope + */ def createChild( - name: String, - scope: AliasScope - ): ExpressionProcessor = { + name: String, + scope: AliasScope + ): ExpressionProcessor = { new ExpressionProcessor(this.scope.createChild(scope), name) } // === Runner ============================================================= /** Runs the code generation process on the provided piece of [[IR]]. - * - * @param ir the IR to generate code for - * @return a truffle expression that represents the same program as `ir` - */ + * + * @param ir the IR to generate code for + * @return a truffle expression that represents the same program as `ir` + */ def run(ir: IR.Expression): RuntimeExpression = { val runtimeExpression = ir match { - case block: IR.Expression.Block => processBlock(block) - case literal: IR.Literal => processLiteral(literal) - case app: IR.Application => processApplication(app) - case name: IR.Name => processName(name) - case function: IR.Function => processFunction(function) + case block: IR.Expression.Block => processBlock(block) + case literal: IR.Literal => processLiteral(literal) + case app: IR.Application => processApplication(app) + case name: IR.Name => processName(name) + case function: IR.Function => processFunction(function) case binding: IR.Expression.Binding => processBinding(binding) - case caseExpr: IR.Case => processCase(caseExpr) - case typ: IR.Type => processType(typ) + case caseExpr: IR.Case => processCase(caseExpr) + case typ: IR.Type => processType(typ) case _: IR.Empty => throw new CompilerError( "Empty IR nodes should not exist during code generation." @@ -603,11 +668,11 @@ class IrToTruffle( } /** Executes the expression processor on a piece of code that has been - * written inline. - * - * @param ir the IR to generate code for - * @return a truffle expression that represents the same program as `ir` - */ + * written inline. + * + * @param ir the IR to generate code for + * @return a truffle expression that represents the same program as `ir` + */ def runInline(ir: IR.Expression): RuntimeExpression = { val expression = run(ir) expression @@ -616,10 +681,10 @@ class IrToTruffle( // === Processing ========================================================= /** Performs code generation for an Enso block expression. - * - * @param block the block to generate code for - * @return the truffle nodes corresponding to `block` - */ + * + * @param block the block to generate code for + * @return the truffle nodes corresponding to `block` + */ def processBlock(block: IR.Expression.Block): RuntimeExpression = { if (block.suspended) { val scopeInfo = block @@ -630,7 +695,7 @@ class IrToTruffle( .unsafeAs[AliasAnalysis.Info.Scope.Child] val childFactory = this.createChild("suspended-block", scopeInfo.scope) - val childScope = childFactory.scope + val childScope = childFactory.scope val blockNode = childFactory.processBlock(block.copy(suspended = false)) @@ -647,7 +712,7 @@ class IrToTruffle( setLocation(CreateThunkNode.build(callTarget), block.location) } else { val statementExprs = block.expressions.map(this.run).toArray - val retExpr = this.run(block.returnValue) + val retExpr = this.run(block.returnValue) val blockNode = BlockNode.build(statementExprs, retExpr) setLocation(blockNode, block.location) @@ -655,10 +720,10 @@ class IrToTruffle( } /** Performs code generation for an Enso type operator. - * - * @param value the type operation to generate code for - * @return the truffle nodes corresponding to `value` - */ + * + * @param value the type operation to generate code for + * @return the truffle nodes corresponding to `value` + */ def processType(value: IR.Type): RuntimeExpression = { setLocation( ErrorNode.build( @@ -675,16 +740,16 @@ class IrToTruffle( } /** Performs code generation for an Enso case expression. - * - * @param caseExpr the case expression to generate code for - * @return the truffle nodes corresponding to `caseExpr` - */ + * + * @param caseExpr the case expression to generate code for + * @return the truffle nodes corresponding to `caseExpr` + */ def processCase(caseExpr: IR.Case): RuntimeExpression = caseExpr match { case IR.Case.Expr(scrutinee, branches, location, _, _) => val scrutineeNode = this.run(scrutinee) - val maybeCases = branches.map(processCaseBranch) + val maybeCases = branches.map(processCaseBranch) val allCasesValid = maybeCases.forall(_.isRight) if (allCasesValid) { @@ -718,14 +783,14 @@ class IrToTruffle( } /** Performs code generation for an Enso case branch. - * - * @param branch the case branch to generate code for - * @return the truffle nodes correspondingg to `caseBranch` or an error if - * the match is invalid - */ + * + * @param branch the case branch to generate code for + * @return the truffle nodes correspondingg to `caseBranch` or an error if + * the match is invalid + */ def processCaseBranch( - branch: IR.Case.Branch - ): Either[BadPatternMatch, BranchNode] = { + branch: IR.Case.Branch + ): Either[BadPatternMatch, BranchNode] = { val scopeInfo = branch .unsafeGetMetadata( AliasAnalysis, @@ -736,7 +801,7 @@ class IrToTruffle( val childProcessor = this.createChild("case_branch", scopeInfo.scope) branch.pattern match { - case named@Pattern.Name(_, _, _, _) => + case named @ Pattern.Name(_, _, _, _) => val arg = List(genArgFromMatchField(named)) val branchCodeNode = childProcessor.processFunctionBody( @@ -749,11 +814,11 @@ class IrToTruffle( CatchAllBranchNode.build(branchCodeNode.getCallTarget) Right(branchNode) - case cons@Pattern.Constructor(constructor, _, _, _, _) => + case cons @ Pattern.Constructor(constructor, _, _, _, _) => if (!cons.isDesugared) { throw new CompilerError( "Nested patterns desugaring must have taken place by the " + - "point of code generation." + "point of code generation." ) } @@ -765,37 +830,37 @@ class IrToTruffle( case None => Left(BadPatternMatch.NonVisibleConstructor(constructor.name)) case Some( - BindingsMap.Resolution(BindingsMap.ResolvedModule(mod)) - ) => + BindingsMap.Resolution(BindingsMap.ResolvedModule(mod)) + ) => Right(mod.unsafeAsModule().getScope.getAssociatedType) case Some( - BindingsMap.Resolution( - BindingsMap.ResolvedConstructor(mod, cons) - ) - ) => + BindingsMap.Resolution( + BindingsMap.ResolvedConstructor(mod, cons) + ) + ) => Right( mod.unsafeAsModule().getScope.getConstructors.get(cons.name) ) case Some( - BindingsMap.Resolution( - BindingsMap.ResolvedPolyglotSymbol(_, _) - ) - ) => + BindingsMap.Resolution( + BindingsMap.ResolvedPolyglotSymbol(_, _) + ) + ) => throw new CompilerError( "Impossible polyglot symbol here, should be caught by Patterns resolution pass." ) case Some( - BindingsMap.Resolution( - BindingsMap.ResolvedMethod(_, _) - ) - ) => + BindingsMap.Resolution( + BindingsMap.ResolvedMethod(_, _) + ) + ) => throw new CompilerError( "Impossible method here, should be caught by Patterns resolution pass." ) } } - val fieldNames = cons.unsafeFieldsAsNamed + val fieldNames = cons.unsafeFieldsAsNamed val fieldsAsArgs = fieldNames.map(genArgFromMatchField) val branchCodeNode = childProcessor.processFunctionBody( @@ -805,14 +870,14 @@ class IrToTruffle( ) runtimeConsOpt.map { atomCons => - val any = context.getBuiltins.any - val array = context.getBuiltins.array - val bool = context.getBuiltins.bool - val builtinTrue = context.getBuiltins.trueAtom + val any = context.getBuiltins.any + val array = context.getBuiltins.array + val bool = context.getBuiltins.bool + val builtinTrue = context.getBuiltins.trueAtom val builtinFalse = context.getBuiltins.falseAtom - val number = context.getBuiltins.number - val polyglot = context.getBuiltins.polyglot - val text = context.getBuiltins.text + val number = context.getBuiltins.number + val polyglot = context.getBuiltins.polyglot + val text = context.getBuiltins.text val branchNode: BranchNode = if (atomCons == builtinTrue) { BooleanBranchNode.build(true, branchCodeNode.getCallTarget) @@ -856,11 +921,11 @@ class IrToTruffle( "Branch documentation should be desugared at an earlier stage." ) case IR.Error.Pattern( - _, - IR.Error.Pattern.WrongArity(name, expected, actual), - _, - _ - ) => + _, + IR.Error.Pattern.WrongArity(name, expected, actual), + _, + _ + ) => Left(BadPatternMatch.WrongArgCount(name, expected, actual)) } @@ -876,10 +941,10 @@ class IrToTruffle( */ /** Generates an argument from a field of a pattern match. - * - * @param name the pattern field to generate from - * @return `name` as a function definition argument. - */ + * + * @param name the pattern field to generate from + * @return `name` as a function definition argument. + */ def genArgFromMatchField(name: Pattern.Name): IR.DefinitionArgument = { IR.DefinitionArgument.Specified( name.name, @@ -887,16 +952,16 @@ class IrToTruffle( None, suspended = false, name.location, - passData = name.name.passData, + passData = name.name.passData, diagnostics = name.name.diagnostics ) } /** Generates code for an Enso binding expression. - * - * @param binding the binding to generate code for - * @return the truffle nodes corresponding to `binding` - */ + * + * @param binding the binding to generate code for + * @return the truffle nodes corresponding to `binding` + */ def processBinding(binding: IR.Expression.Binding): RuntimeExpression = { val occInfo = binding .unsafeGetMetadata( @@ -916,10 +981,10 @@ class IrToTruffle( } /** Generates code for an Enso function. - * - * @param function the function to generate code for - * @return the truffle nodes corresponding to `function` - */ + * + * @param function the function to generate code for + * @return the truffle nodes corresponding to `function` + */ def processFunction(function: IR.Function): RuntimeExpression = { val scopeInfo = function .unsafeGetMetadata(AliasAnalysis, "No scope info on a function.") @@ -928,7 +993,7 @@ class IrToTruffle( if (function.body.isInstanceOf[IR.Function]) { throw new CompilerError( "Lambda found directly as function body. It looks like Lambda " + - "Consolidation hasn't run." + "Consolidation hasn't run." ) } @@ -950,10 +1015,10 @@ class IrToTruffle( } /** Generates code for an Enso name. - * - * @param name the name to generate code for - * @return the truffle nodes corresponding to `name` - */ + * + * @param name the name to generate code for + * @return the truffle nodes corresponding to `name` + */ def processName(name: IR.Name): RuntimeExpression = { val nameExpr = name match { case IR.Name.Literal(nameStr, _, _, _, _, _) => @@ -964,7 +1029,7 @@ class IrToTruffle( ) .unsafeAs[AliasAnalysis.Info.Occurrence] - val slot = scope.getFramePointer(useInfo.id) + val slot = scope.getFramePointer(useInfo.id) val global = name.getMetadata(UppercaseNames) if (slot.isDefined) { ReadLocalVariableNode.build(slot.get) @@ -1010,16 +1075,16 @@ class IrToTruffle( IR.Name.Literal( Constants.Names.THIS_ARGUMENT, isReferent = false, - isMethod = false, + isMethod = false, location, passData ) ) case IR.Name.Special(name, _, _, _) => val fun = name match { - case Special.NewRef => context.getBuiltins.special().getNewRef - case Special.ReadRef => context.getBuiltins.special().getReadRef - case Special.WriteRef => context.getBuiltins.special().getWriteRef + case Special.NewRef => context.getBuiltins.special().getNewRef + case Special.ReadRef => context.getBuiltins.special().getReadRef + case Special.WriteRef => context.getBuiltins.special().getWriteRef case Special.RunThread => context.getBuiltins.special().getRunThread case Special.JoinThread => context.getBuiltins.special().getJoinThread @@ -1049,21 +1114,20 @@ class IrToTruffle( } /** Generates code for an Enso literal. - * - * @param literal the literal to generate code for - * @return the truffle nodes corresponding to `literal` - */ + * + * @param literal the literal to generate code for + * @return the truffle nodes corresponding to `literal` + */ def processLiteral(literal: IR.Literal): RuntimeExpression = literal match { - case lit@IR.Literal.Number(base, value, location, _, _) => + case lit @ IR.Literal.Number(base, value, location, _, _) => val node = if (lit.isFractional) { DecimalLiteralNode.build(value.toDouble) } else if (base.isDefined) { val baseNum = try { Integer.parseInt(base.get) - } - catch { + } catch { case _: NumberFormatException => throw new CompilerError( s"Invalid number base $base seen during codegen." @@ -1095,10 +1159,10 @@ class IrToTruffle( } /** Generates a runtime implementation for compile error nodes. - * - * @param error the IR representing a compile error. - * @return a runtime node representing the error. - */ + * + * @param error the IR representing a compile error. + * @return a runtime node representing the error. + */ def processError(error: IR.Error): RuntimeExpression = { val payload: AnyRef = error match { case Error.InvalidIR(_, _, _) => @@ -1156,22 +1220,22 @@ class IrToTruffle( } /** Processes function arguments, generates arguments reads and creates - * a node to represent the whole method body. - * - * @param arguments the argument definitions - * @param body the body definition - * @return a node for the final shape of function body and pre-processed - * argument definitions. - */ + * a node to represent the whole method body. + * + * @param arguments the argument definitions + * @param body the body definition + * @return a node for the final shape of function body and pre-processed + * argument definitions. + */ def buildFunctionBody( - arguments: List[IR.DefinitionArgument], - body: IR.Expression - ): (BlockNode, Array[ArgumentDefinition]) = { + arguments: List[IR.DefinitionArgument], + body: IR.Expression + ): (BlockNode, Array[ArgumentDefinition]) = { val argFactory = new DefinitionArgumentProcessor(scopeName, scope) val argDefinitions = new Array[ArgumentDefinition](arguments.size) val argExpressions = new ArrayBuffer[RuntimeExpression] - val seenArgNames = mutable.Set[String]() + val seenArgNames = mutable.Set[String]() // Note [Rewriting Arguments] val argSlots = @@ -1219,11 +1283,11 @@ class IrToTruffle( } private def buildForeignBody( - language: EpbParser.ForeignLanguage, - code: String, - argumentNames: List[String], - argumentSlots: List[FrameSlot] - ): RuntimeExpression = { + language: EpbParser.ForeignLanguage, + code: String, + argumentNames: List[String], + argumentSlots: List[FrameSlot] + ): RuntimeExpression = { val src = EpbParser.buildSource(language, code, scopeName) val foreignCt = context.getEnvironment .parseInternal(src, argumentNames: _*) @@ -1234,17 +1298,17 @@ class IrToTruffle( } /** Generates code for an Enso function body. - * - * @param arguments the arguments to the function - * @param body the body of the function - * @param location the location at which the function exists in the source - * @return a truffle node representing the described function - */ + * + * @param arguments the arguments to the function + * @param body the body of the function + * @param location the location at which the function exists in the source + * @return a truffle node representing the described function + */ def processFunctionBody( - arguments: List[IR.DefinitionArgument], - body: IR.Expression, - location: Option[IdentifiedLocation] - ): CreateFunctionNode = { + arguments: List[IR.DefinitionArgument], + body: IR.Expression, + location: Option[IdentifiedLocation] + ): CreateFunctionNode = { val (fnBodyNode, argDefinitions) = buildFunctionBody(arguments, body) val fnRootNode = ClosureRootNode.build( language, @@ -1286,17 +1350,17 @@ class IrToTruffle( */ /** Generates code for an Enso function application. - * - * @param application the function application to generate code for - * @return the truffle nodes corresponding to `application` - */ + * + * @param application the function application to generate code for + * @return the truffle nodes corresponding to `application` + */ def processApplication(application: IR.Application): RuntimeExpression = application match { case IR.Application.Prefix(fn, args, hasDefaultsSuspended, loc, _, _) => val callArgFactory = new CallArgumentProcessor(scope, scopeName) val arguments = args - val callArgs = new ArrayBuffer[CallArgument]() + val callArgs = new ArrayBuffer[CallArgument]() for ((unprocessedArg, position) <- arguments.view.zipWithIndex) { val arg = callArgFactory.run(unprocessedArg, position) @@ -1311,8 +1375,8 @@ class IrToTruffle( val appNode = application.getMetadata(ApplicationSaturation) match { case Some( - ApplicationSaturation.CallSaturation.Exact(createOptimised) - ) => + ApplicationSaturation.CallSaturation.Exact(createOptimised) + ) => createOptimised(moduleScope)(scope)(callArgs.toList) case _ => ApplicationNode.build( @@ -1348,7 +1412,7 @@ class IrToTruffle( case sec: IR.Application.Operator.Section => throw new CompilerError( s"Explicit operator sections not supported during codegen but " + - s"$sec found" + s"$sec found" ) } } @@ -1358,34 +1422,34 @@ class IrToTruffle( // ========================================================================== /** Performs codegen for call-site arguments in Enso. - * - * @param scope the scope in which the function call exists - * @param scopeName the name of `scope` - */ + * + * @param scope the scope in which the function call exists + * @param scopeName the name of `scope` + */ sealed private class CallArgumentProcessor( - val scope: LocalScope, - val scopeName: String - ) { + val scope: LocalScope, + val scopeName: String + ) { // === Runner ============================================================= /** Executes codegen on the call-site argument. - * - * @param arg the argument definition - * @param position the position of the argument at the call site - * @return a truffle construct corresponding to the argument definition - * `arg` - */ + * + * @param arg the argument definition + * @param position the position of the argument at the call site + * @return a truffle construct corresponding to the argument definition + * `arg` + */ def run(arg: IR.CallArgument, position: Int): CallArgument = arg match { case IR.CallArgument.Specified( - name, - value, - _, - shouldBeSuspended, - _, - _ - ) => + name, + value, + _, + shouldBeSuspended, + _, + _ + ) => val scopeInfo = arg .unsafeGetMetadata( AliasAnalysis, @@ -1394,8 +1458,8 @@ class IrToTruffle( .unsafeAs[AliasAnalysis.Info.Scope.Child] val shouldSuspend = value match { - case _: IR.Name => false - case _: IR.Literal.Text => false + case _: IR.Name => false + case _: IR.Literal.Text => false case _: IR.Literal.Number => false case _ => shouldBeSuspended.getOrElse( @@ -1463,14 +1527,14 @@ class IrToTruffle( // ========================================================================== /** Performs codegen for definition-site arguments in Enso. - * - * @param scope the scope in which the function is defined - * @param scopeName the name of `scope` - */ + * + * @param scope the scope in which the function is defined + * @param scopeName the name of `scope` + */ sealed private class DefinitionArgumentProcessor( - val scopeName: String = "", - val scope: LocalScope - ) { + val scopeName: String = "", + val scope: LocalScope + ) { // === Runner ============================================================= @@ -1485,16 +1549,16 @@ class IrToTruffle( */ /** Executes the code generator on the provided definition-site argument. - * - * @param inputArg the argument to generate code for - * @param position the position of `arg` at the function definition site - * @return a truffle entity corresponding to the definition of `arg` for a - * given function - */ + * + * @param inputArg the argument to generate code for + * @param position the position of `arg` at the function definition site + * @return a truffle entity corresponding to the definition of `arg` for a + * given function + */ def run( - inputArg: IR.DefinitionArgument, - position: Int - ): ArgumentDefinition = + inputArg: IR.DefinitionArgument, + position: Int + ): ArgumentDefinition = inputArg match { case arg: IR.DefinitionArgument.Specified => val defaultExpression = arg.defaultValue diff --git a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala index bdf9c7beab7a..c59b0d84045a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala @@ -2049,7 +2049,7 @@ object IR { override def children: List[IR] = List() /** @inheritdoc */ - override def showCode(indent: Int): String = s"\"$text\"" + override def showCode(indent: Int): String = s""""$text"""" } } @@ -4312,7 +4312,7 @@ object IR { res } - override def withName(ir: Name): DefinitionArgument = copy(name=ir) + override def withName(ir: Name): DefinitionArgument = copy(name = ir) /** @inheritdoc */ override def duplicate( @@ -6373,8 +6373,9 @@ object IR { * with unexpected body. * @param location the location of the annotated application */ - case class WrongBuiltinMethod(override val location: Option[IdentifiedLocation]) - extends Warning { + case class WrongBuiltinMethod( + override val location: Option[IdentifiedLocation] + ) extends Warning { override def message: String = "A @Builtin_Method annotation allows only the name of the builtin node in the body." } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index 89cad74bd638..5df6344fb921 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala @@ -720,7 +720,12 @@ object BindingsMap { * @param allFieldsDefaulted whether all fields provide a default value. * @param builtinType true if constructor is annotated with @Builtin_Type, false otherwise. */ - case class Cons(name: String, arity: Int, allFieldsDefaulted: Boolean, builtinType: Boolean = false) + case class Cons( + name: String, + arity: Int, + allFieldsDefaulted: Boolean, + builtinType: Boolean = false + ) /** A representation of an imported polyglot symbol. * diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala index 9218c6b27db8..4c63b202825a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala @@ -6,8 +6,16 @@ import org.enso.compiler.core.ir.MetadataStorage.ToPair import org.enso.compiler.data.BindingsMap import org.enso.compiler.data.BindingsMap.ModuleReference import org.enso.compiler.pass.IRPass -import org.enso.compiler.pass.desugar.{ComplexType, FunctionBinding, GenerateMethodBodies} -import org.enso.compiler.pass.resolve.{MethodDefinitions, ModuleAnnotations, Patterns} +import org.enso.compiler.pass.desugar.{ + ComplexType, + FunctionBinding, + GenerateMethodBodies +} +import org.enso.compiler.pass.resolve.{ + MethodDefinitions, + ModuleAnnotations, + Patterns +} import scala.annotation.unused diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala index 6005ef7ad390..b6726e9986d4 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala @@ -119,8 +119,13 @@ case object ComplexType extends IRPass { // Annotations of Atoms in Complex Types were being overwritten. We want to make sure that // we only append the annotations of complex types without errasing the former. // FIXME check if there is a nicer way of doing this - val old = atom.getMetadata(ModuleAnnotations).map(_.annotations).getOrElse(Nil) - atom.updateMetadata(ModuleAnnotations -->> ann.copy(ann.annotations ++ old)) + val old = atom + .getMetadata(ModuleAnnotations) + .map(_.annotations) + .getOrElse(Nil) + atom.updateMetadata( + ModuleAnnotations -->> ann.copy(ann.annotations ++ old) + ) }) .getOrElse(atom) ) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala index 3758bcea82b6..dee34d0ebf3e 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala @@ -140,14 +140,17 @@ case object UnusedBindings extends IRPass { if (isBuiltin) args else args.map(lintFunctionArgument(_, context)) val body1 = runExpression(body, context) - val lintedBody = if (isBuiltin) - body match { - case _: IR.Literal.Text => - body1 - case _ => - body1.addDiagnostic(IR.Warning.WrongBuiltinMethod(body.location)) - } - else body1 + val lintedBody = + if (isBuiltin) + body match { + case _: IR.Literal.Text => + body1 + case _ => + body1.addDiagnostic( + IR.Warning.WrongBuiltinMethod(body.location) + ) + } + else body1 lam.copy( arguments = lintedArgs, @@ -282,8 +285,9 @@ case object UnusedBindings extends IRPass { private def isBuiltinMethod(expression: IR.Expression): Boolean = { expression .getMetadata(ExpressionAnnotations) - .exists(_.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName)) + .exists( + _.annotations.exists(_.name == ExpressionAnnotations.builtinMethodName) + ) } - } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index 2dbd0c040bca..1aec13fc1fd9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -7,7 +7,11 @@ import org.enso.compiler.data.BindingsMap import org.enso.compiler.exception.CompilerError import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis -import org.enso.compiler.pass.desugar.{ComplexType, FunctionBinding, GenerateMethodBodies} +import org.enso.compiler.pass.desugar.{ + ComplexType, + FunctionBinding, + GenerateMethodBodies +} import scala.annotation.unused diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index 20025dc11eb4..c4b323de16ea 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -114,8 +114,8 @@ case object OverloadsResolution extends IRPass { } } - val diagnostics = ir.bindings.collect { - case diag: IR.Diagnostic => diag + val diagnostics = ir.bindings.collect { case diag: IR.Diagnostic => + diag } ir.copy( diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala index e0f612fe8a90..a9a4dd4538ab 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala @@ -24,11 +24,11 @@ class DetachVisualisationCmd( ): Future[Unit] = { ctx.locking.acquireContextLock(request.contextId) try { - if (doesContextExist) { - detachVisualization() - } else { - replyWithContextNotExistError() - } + if (doesContextExist) { + detachVisualization() + } else { + replyWithContextNotExistError() + } } finally { ctx.locking.releaseContextLock(request.contextId) } diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala index f936635aa2c2..ba0c6e5d356c 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala @@ -29,11 +29,11 @@ class ModifyVisualisationCmd( val contextId = request.visualisationConfig.executionContextId ctx.locking.acquireContextLock(contextId) try { - if (doesContextExist) { - modifyVisualisation() - } else { - replyWithContextNotExistError() - } + if (doesContextExist) { + modifyVisualisation() + } else { + replyWithContextNotExistError() + } } finally { ctx.locking.releaseContextLock(contextId) } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/GenerateMethodBodiesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/GenerateMethodBodiesTest.scala index 74d8c5bb73bb..18c226eb06f4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/GenerateMethodBodiesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/GenerateMethodBodiesTest.scala @@ -146,7 +146,7 @@ class GenerateMethodBodiesTest extends CompilerTest { val conversion = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Method] - conversion.body shouldBe an [IR.Error.Redefined.ThisArg] + conversion.body shouldBe an[IR.Error.Redefined.ThisArg] } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala index 74c0174596aa..88600209e17c 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala @@ -45,7 +45,8 @@ class OperatorToFunctionTest extends CompilerTest { // === The Tests ============================================================ "Operators" should { - val opName = IR.Name.Literal("=:=", isReferent = false,isMethod = true, None) + val opName = + IR.Name.Literal("=:=", isReferent = false, isMethod = true, None) val left = IR.Empty(None) val right = IR.Empty(None) val rightArg = IR.CallArgument.Specified(None, IR.Empty(None), None) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/ApplicationSaturationTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/ApplicationSaturationTest.scala index b15a7e711178..38df6e013e2b 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/ApplicationSaturationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/ApplicationSaturationTest.scala @@ -6,7 +6,11 @@ import org.enso.compiler.core.IR import org.enso.compiler.pass.PassConfiguration._ import org.enso.compiler.pass.analyse.{AliasAnalysis, TailCall} import org.enso.compiler.pass.optimise.ApplicationSaturation -import org.enso.compiler.pass.optimise.ApplicationSaturation.{CallSaturation, FunctionSpec, Metadata} +import org.enso.compiler.pass.optimise.ApplicationSaturation.{ + CallSaturation, + FunctionSpec, + Metadata +} import org.enso.compiler.pass.{PassConfiguration, PassManager} import org.enso.compiler.test.CompilerTest import org.enso.interpreter.node.ExpressionNode diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala index ee53f9015647..ded12908b5e9 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala @@ -224,8 +224,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { | ## Do another thing | z = x * y |""".stripMargin.preprocessModule.resolve - val body = ir - .bindings.head + val body = ir.bindings.head .asInstanceOf[IR.Module.Scope.Definition.Method.Binding] .body .asInstanceOf[IR.Expression.Block] @@ -247,8 +246,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { | ## Return thing | f 1 |""".stripMargin.preprocessModule.resolve - val body = ir - .bindings.head + val body = ir.bindings.head .asInstanceOf[IR.Module.Scope.Definition.Method.Binding] .body .asInstanceOf[IR.Expression.Block] diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleThisToHereTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleThisToHereTest.scala index 36aa4bd7ad14..32de214b3fc3 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleThisToHereTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleThisToHereTest.scala @@ -89,7 +89,7 @@ class ModuleThisToHereTest extends CompilerTest { .body .asInstanceOf[IR.Function.Lambda] .body - val children = method2.preorder + val children = method2.preorder val thisOccurrences = children.collect { case n: IR.Name.This => n } val hereOccurrences = children.collect { case n: IR.Name.Here => n } thisOccurrences.length shouldEqual 0 @@ -103,7 +103,7 @@ class ModuleThisToHereTest extends CompilerTest { .body .asInstanceOf[IR.Function.Lambda] .body - val children = method1.preorder + val children = method1.preorder val thisOccurrences = children.collect { case n: IR.Name.This => n } val hereOccurrences = children.collect { case n: IR.Name.Here => n } thisOccurrences.length shouldEqual 6 @@ -117,9 +117,9 @@ class ModuleThisToHereTest extends CompilerTest { .body .asInstanceOf[IR.Function.Lambda] .body - val children = conv1.preorder - val thisOccurrences = children.collect { case n: IR.Name.This => n} - val hereOccurrences = children.collect { case n: IR.Name.Here => n} + val children = conv1.preorder + val thisOccurrences = children.collect { case n: IR.Name.This => n } + val hereOccurrences = children.collect { case n: IR.Name.Here => n } thisOccurrences.length shouldEqual 0 hereOccurrences.length shouldEqual 7 } @@ -131,9 +131,9 @@ class ModuleThisToHereTest extends CompilerTest { .body .asInstanceOf[IR.Function.Lambda] .body - val children = conv2.preorder - val thisOccurrences = children.collect { case n: IR.Name.This => n} - val hereOccurrences = children.collect { case n: IR.Name.Here => n} + val children = conv2.preorder + val thisOccurrences = children.collect { case n: IR.Name.This => n } + val hereOccurrences = children.collect { case n: IR.Name.Here => n } thisOccurrences.length shouldEqual 6 hereOccurrences.length shouldEqual 1 } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala index 308760dffdda..8c8a49abcdc7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -20,19 +20,24 @@ class InstrumentTestContext { Option(messageQueue.poll(timeoutSeconds, TimeUnit.SECONDS)) } - def receiveN(n: Int, timeoutSeconds: Long=10): List[Api.Response] = { - Iterator.continually(receiveWithTimeout(timeoutSeconds)).take(n).flatten.toList + def receiveN(n: Int, timeoutSeconds: Long = 10): List[Api.Response] = { + Iterator + .continually(receiveWithTimeout(timeoutSeconds)) + .take(n) + .flatten + .toList } def receiveNIgnoreStdLib(n: Int): List[Api.Response] = { - receiveN(n+1, 50).filter(excludeLibraryLoadingPayload) + receiveN(n + 1, 50).filter(excludeLibraryLoadingPayload) } - private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = response match { - case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => - false - case _ => - true - } + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = + response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 5bf5e9b79472..87813ad85d45 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -472,7 +472,7 @@ class RuntimeErrorsTest ) ) ) - context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq ( + context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index ac8d49b3a1a3..ebf01dad44f7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -1569,7 +1569,7 @@ class RuntimeServerTest Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") ), TestMessages.update( - contextId, + contextId, id3, Constants.INTEGER, Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") @@ -2675,8 +2675,8 @@ class RuntimeServerTest val code = """main = - | x = 1 - |""".stripMargin.linesIterator.mkString("\n") + | x = 1 + |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) val mainFile = context.writeMain(contents) @@ -2784,10 +2784,10 @@ class RuntimeServerTest } it should "return compiler error variable redefined" in { - val contextId = UUID.randomUUID() - val requestId = UUID.randomUUID() + val contextId = UUID.randomUUID() + val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val metadata = new Metadata + val metadata = new Metadata val code = """main = @@ -3164,7 +3164,7 @@ class RuntimeServerTest } it should "send the type graph" in { - val requestId = UUID.randomUUID() + val requestId = UUID.randomUUID() val expectedGraph: TypeGraph = Types.getTypeHierarchy context.send(Api.Request(requestId, Api.GetTypeGraphRequest())) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index a7a9bb38c38a..fa40ea7d1495 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -248,7 +248,7 @@ class RuntimeVisualisationsTest } it should "emit visualisation update when expression is computed" in { - val idMainRes = context.Main.metadata.addItem(107, 1) + val idMainRes = context.Main.metadata.addItem(107, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1689,7 +1689,7 @@ class RuntimeVisualisationsTest ) val responses = context.receiveN(n = 4, timeoutSeconds = 60) - responses should contain allOf( + responses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index 3ac9ea9d6506..b4e6364f7a9a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala @@ -8,7 +8,7 @@ class CompileDiagnosticsTest extends InterpreterTest { override def specify(implicit interpreterContext: InterpreterContext ): Unit = { - "surface ast-processing errors in the language" in { + "surface ast-processing errors in the language" in { val code = """from Standard.Base.Error.Common import all | @@ -34,7 +34,7 @@ class CompileDiagnosticsTest extends InterpreterTest { eval(code) shouldEqual "(Syntax_Error 'Unrecognized token.')" } - "surface redefinition errors in the language" in { + "surface redefinition errors in the language" in { val code = """from Standard.Base.Error.Common import all | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala index 4e7539f13bab..775456a166a7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DataflowErrorsTest.scala @@ -201,7 +201,7 @@ class DataflowErrorsTest extends InterpreterTest { eval(code) consumeOut shouldEqual List( "(Error: (Syntax_Error 'Unrecognized token.'))", - "(Syntax_Error 'Unrecognized token.')", + "(Syntax_Error 'Unrecognized token.')" ) } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index 79f88273d787..789fdbbb70bb 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala @@ -301,7 +301,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { | result.stdout |""".stripMargin - val result = eval(code).asString().replace("\r\n","\n") + val result = eval(code).asString().replace("\r\n", "\n") result shouldEqual "foobar\n" consumeOut shouldEqual List() consumeErr shouldEqual List() @@ -318,7 +318,7 @@ class SystemProcessTest extends InterpreterTest with OsSpec { | result.stdout |""".stripMargin - val result = eval(code).asString().replace("\r\n","\n") + val result = eval(code).asString().replace("\r\n", "\n") result shouldEqual "foobar\n" consumeOut shouldEqual List() consumeErr shouldEqual List() diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java index d6be2ffb0f83..9e878135e300 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -9,10 +9,11 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface BuiltinType { - /** - * Comma-separated list of parameters of builting type - * @return list of params - */ - // FIXME: - String params() default ""; + /** + * Comma-separated list of parameters of builting type + * + * @return list of params + */ + // FIXME: + String params() default ""; } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index d4b29a53eb04..34ff2eb48846 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -15,72 +15,73 @@ public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { - protected abstract String metadataPath(); + protected abstract String metadataPath(); - protected abstract void cleanup(); + protected abstract void cleanup(); - protected abstract void storeMetadata(Writer writer, Map pastEntries) throws IOException; + protected abstract void storeMetadata(Writer writer, Map pastEntries) + throws IOException; - @Override - public final boolean process(Set annotations, RoundEnvironment roundEnv) { - if (roundEnv.errorRaised()) { - return false; + @Override + public final boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.errorRaised()) { + return false; + } + if (roundEnv.processingOver()) { + // A hack to improve support for separate compilation. + // Since one cannot open the existing resource file in Append mode, + // we read the whole file and provide to the function that does the update. + // Deletes/renaming is still not gonna work but that would be the same case + // if we were writing metadata information per source file anyway. + Map pastEntries; + try { + FileObject existingFile = + processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); + try (InputStream resource = existingFile.openInputStream()) { + pastEntries = + new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.toMap(l -> l.split(":")[0], Function.identity())); } - if (roundEnv.processingOver()) { - // A hack to improve support for separate compilation. - // Since one cannot open the existing resource file in Append mode, - // we read the whole file and provide to the function that does the update. - // Deletes/renaming is still not gonna work but that would be the same case - // if we were writing metadata information per source file anyway. - Map pastEntries; - try { - FileObject existingFile = processingEnv.getFiler().getResource( - StandardLocation.CLASS_OUTPUT, "", - metadataPath()); - try (InputStream resource = existingFile.openInputStream()) { - pastEntries = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)). - lines(). - collect(Collectors.toMap(l -> l.split(":")[0], Function.identity())); - } - } catch (NoSuchFileException notFoundException) { - pastEntries = new HashMap<>(); - } catch (Exception e) { - e.printStackTrace(); - pastEntries = new HashMap<>(); - } - try { - FileObject res = processingEnv.getFiler().createResource( - StandardLocation.CLASS_OUTPUT, "", - metadataPath() - ); - Writer writer = res.openWriter(); - try { - storeMetadata(writer, pastEntries); - // Separate compilation hack - for (String value: pastEntries.values()) { - writer.append(value + "\n"); - } - } finally { - writer.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - cleanup(); - return true; - } else { - return handleProcess(annotations, roundEnv); + } catch (NoSuchFileException notFoundException) { + pastEntries = new HashMap<>(); + } catch (Exception e) { + e.printStackTrace(); + pastEntries = new HashMap<>(); + } + try { + FileObject res = + processingEnv + .getFiler() + .createResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); + Writer writer = res.openWriter(); + try { + storeMetadata(writer, pastEntries); + // Separate compilation hack + for (String value : pastEntries.values()) { + writer.append(value + "\n"); + } + } finally { + writer.close(); } + } catch (IOException e) { + e.printStackTrace(); + } + cleanup(); + return true; + } else { + return handleProcess(annotations, roundEnv); } + } - /** - * The regular body of {@link #process}. - * Called during regular rounds if there are no outstanding errors. - * In the last round, one of the processors will dump all builtin metadata - * @param annotations as in {@link #process} - * @param roundEnv as in {@link #process} - * @return as in {@link #process} - */ - protected abstract boolean handleProcess(Set annotations, RoundEnvironment roundEnv); - + /** + * The regular body of {@link #process}. Called during regular rounds if there are no outstanding + * errors. In the last round, one of the processors will dump all builtin metadata + * + * @param annotations as in {@link #process} + * @param roundEnv as in {@link #process} + * @return as in {@link #process} + */ + protected abstract boolean handleProcess( + Set annotations, RoundEnvironment roundEnv); } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index 8ffa0517a008..d492d9017146 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -67,12 +67,13 @@ public boolean handleProcess(Set annotations, RoundEnviro generateCode(def); String tpe = def.getType().toLowerCase(); if (tpe.isEmpty()) { - throw new InternalError("Type of the BuiltinMethod cannot be empty in: " + def.getClassName()); + throw new InternalError( + "Type of the BuiltinMethod cannot be empty in: " + def.getClassName()); } String fullClassName = def.getPackageName() + "." + def.getClassName(); registerBuiltinMethod(processingEnv.getFiler(), def.getDeclaredName(), fullClassName); if (def.hasAliases()) { - for (String alias: def.aliases()) { + for (String alias : def.aliases()) { registerBuiltinMethod(processingEnv.getFiler(), alias, fullClassName); } } @@ -87,7 +88,7 @@ public boolean handleProcess(Set annotations, RoundEnviro } protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { - for (Filer f: builtinMethods.keySet()) { + for (Filer f : builtinMethods.keySet()) { for (Map.Entry entry : builtinMethods.get(f).entrySet()) { writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); if (pastEntries.containsKey(entry.getKey())) { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index dd706ea6f8e8..4644a0abe807 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -16,78 +16,83 @@ @SupportedSourceVersion(SourceVersion.RELEASE_11) @AutoService(Processor.class) public class TypeProcessor extends BuiltinsMetadataProcessor { - private final Map> builtinTypes = new HashMap<>(); + private final Map> builtinTypes = new HashMap<>(); - private class BuiltinTypeConstr { - private String tpeName; - private String paramNames; + private class BuiltinTypeConstr { + private String tpeName; + private String paramNames; - BuiltinTypeConstr(String tpeName, String params) { - this.tpeName = tpeName; - this.paramNames = params; - } - - public String getTpeName() { - return tpeName; - } + BuiltinTypeConstr(String tpeName, String params) { + this.tpeName = tpeName; + this.paramNames = params; + } - public String getParamNames() { - return paramNames; - } + public String getTpeName() { + return tpeName; + } + public String getParamNames() { + return paramNames; } + } + public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; + public static final String META_PATH = + "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinTypes.metadata"; - public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; - public static final String META_PATH = - "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinTypes.metadata"; - @Override - protected String metadataPath() { - return META_PATH; - } + @Override + protected String metadataPath() { + return META_PATH; + } - @Override - protected void cleanup() { - builtinTypes.clear(); - } + @Override + protected void cleanup() { + builtinTypes.clear(); + } - @Override - protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { - for (Filer f: builtinTypes.keySet()) { - for (Map.Entry entry : builtinTypes.get(f).entrySet()) { - BuiltinTypeConstr constr = entry.getValue(); - writer.append(entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); - if (pastEntries.containsKey(entry.getKey())) { - pastEntries.remove(entry.getKey()); - } - } + @Override + protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { + for (Filer f : builtinTypes.keySet()) { + for (Map.Entry entry : builtinTypes.get(f).entrySet()) { + BuiltinTypeConstr constr = entry.getValue(); + writer.append( + entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); } + } } + } - @Override - protected boolean handleProcess(Set annotations, RoundEnvironment roundEnv) { - for (TypeElement annotation : annotations) { - Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); - for (Element elt : annotatedElements) { - TypeElement element = (TypeElement) elt; - BuiltinType builtinTypeAnnotation = element.getAnnotation(BuiltinType.class); - String pkgName = - processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); - String clazzName = element.getSimpleName().toString(); - // Replace CamelCase class name to Snake_Case used in Enso - String ensoTypeName = clazzName.replaceAll("([^_A-Z])([A-Z])", "$1_$2"); - registerBuiltinType(processingEnv.getFiler(), ensoTypeName, pkgName + "." + clazzName, builtinTypeAnnotation.params()); - } - } - return true; + @Override + protected boolean handleProcess( + Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + for (Element elt : annotatedElements) { + TypeElement element = (TypeElement) elt; + BuiltinType builtinTypeAnnotation = element.getAnnotation(BuiltinType.class); + String pkgName = + processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); + String clazzName = element.getSimpleName().toString(); + // Replace CamelCase class name to Snake_Case used in Enso + String ensoTypeName = clazzName.replaceAll("([^_A-Z])([A-Z])", "$1_$2"); + registerBuiltinType( + processingEnv.getFiler(), + ensoTypeName, + pkgName + "." + clazzName, + builtinTypeAnnotation.params()); + } } + return true; + } - protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { - Map classes = builtinTypes.get(f); - if (classes == null) { - classes = new HashMap<>(); - builtinTypes.put(f, classes); - } - classes.put(name, new BuiltinTypeConstr(clazzName, params)); + protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { + Map classes = builtinTypes.get(f); + if (classes == null) { + classes = new HashMap<>(); + builtinTypes.put(f, classes); } + classes.put(name, new BuiltinTypeConstr(clazzName, params)); + } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java index 677fc8704e31..3c1ad6b006d4 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/model/MethodDefinition.java @@ -14,7 +14,7 @@ public class MethodDefinition { private static final String STATEFUL = "org.enso.interpreter.runtime.state.Stateful"; public static final String NODE_PKG = "org.enso.interpreter.node.expression.builtin"; public static final String META_PATH = - "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinMethods.metadata"; + "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinMethods.metadata"; private final String packageName; private final String originalClassName; @@ -60,8 +60,8 @@ public String[] aliases() { return new String[0]; } else { String[] methodNames = annotation.aliases().split(","); - for (int i=0; i> any || text.onEscapeInvalid() text.FMT || "\\" || text.onEscapeUnfinished() - text.FMT_LINE || "'" || text.submit() - text.FMT_LINE || "'".many1 || text.submitInvalidQuote() - text.FMT_LINE || text.fmtSeg || text.submitPlainSegment() - text.FMT_LINE || eof || text.submitMissingQuote() - text.FMT_LINE || newline || text.submitMissingQuote() + text.FMT_LINE || "'" || text.submit() + text.FMT_LINE || "'".many1 || text.submitInvalidQuote() + text.FMT_LINE || text.fmtSeg || text.submitPlainSegment() + text.FMT_LINE || eof || text.submitMissingQuote() + text.FMT_LINE || newline || text.submitMissingQuote() - text.FMT_BLCK || text.fmtBSeg || text.submitPlainSegment() - text.FMT_BLCK || eof || text.onEndOfBlock() - text.FMT_BLCK || newline || text.onEndOfLine() + text.FMT_BLCK || text.fmtBSeg || text.submitPlainSegment() + text.FMT_BLCK || eof || text.onEndOfBlock() + text.FMT_BLCK || newline || text.onEndOfLine() text.RAW_LINE || '"' || text.submit() text.RAW_LINE || '"'.many1 || text.submitInvalidQuote() @@ -669,9 +669,9 @@ case class ParserDef() extends flexer.Parser[AST.Module] { text.RAW_LINE || eof || text.submitMissingQuote() text.RAW_LINE || newline || text.submitMissingQuote() - text.RAW_BLCK || text.rawBSeg || text.submitPlainSegment() - text.RAW_BLCK || eof || text.onEndOfBlock() - text.RAW_BLCK || newline || text.onEndOfLine() + text.RAW_BLCK || text.rawBSeg || text.submitPlainSegment() + text.RAW_BLCK || eof || text.onEndOfBlock() + text.RAW_BLCK || newline || text.onEndOfLine() text.NEWLINE || space.opt || text.onNewLine() text.NEWLINE || space.opt >> newline || text.onEmptyLine() diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala index afd9cf40cfa3..58cbeb013bd7 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala @@ -31,7 +31,7 @@ object model { * * {{{ * 0|inc x = - 1| x + 1 + * 1| x + 1 * ^^^^^^^^^ * 012345678 * }}} From 69ad6693cce7b44698338fdbd862638ab514ce08 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 11:22:04 +0200 Subject: [PATCH 48/73] Remove extension method for unimplemented error --- .../lib/Standard/Base/0.0.0-dev/src/Error/Common.enso | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 795c1ac46b6c..699066131cf3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -536,11 +536,11 @@ type No_Such_Conversion_Error - message: The message describing what implementation is missing. type Unimplemented_Error message -## UNSTABLE + ## UNSTABLE - Converts the unimplemented error to a human-readable error message. -Unimplemented_Error.to_display_text : Text -Unimplemented_Error.to_display_text = "An implementation is missing: " + this.message + Converts the unimplemented error to a human-readable error message. + to_display_text : Text + to_display_text = "An implementation is missing: " + this.message ## ADVANCED From 13723876a0e8a84bea07ee8189955df05798c396 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 14:02:33 +0200 Subject: [PATCH 49/73] Minor adjustments to expectations --- .../org/enso/interpreter/test/instrument/ReplTest.scala | 2 +- .../interpreter/test/instrument/RuntimeServerTest.scala | 7 ++++--- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 5 ++++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 46e35dda2c43..3bade5c99b46 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -72,8 +72,8 @@ class ReplTest "allow to access Text representations of the returned values" in { val code = """ - |from Standard.Builtins import all |polyglot java import java.util.regex.Pattern + |import Standard.Base.Runtime.Debug | |type Foo a b | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index ebf01dad44f7..c395d564a354 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -1385,8 +1385,9 @@ class RuntimeServerTest val id2 = metadata.addItem(159, 18) val id3 = metadata.addItem(182, 15) // Note that Nothing.Nothing is on purpose. - // If not provided the full name it will resolve the - // expression type of Nothing to a Nothing module + // If not provided the full name it will resolve the expression Nothing to a Nothing module. + // Similarly Text.Text. That in turn will mismatch the expectations for method types which actually + // return proper types. val code = """from Standard.Base.Data.Number.Internal import Number |from Standard.Base.Data.Text import all @@ -1398,7 +1399,7 @@ class RuntimeServerTest | 10.overloaded x | Nothing.Nothing | - |Text.overloaded arg = arg + 1 + |Text.Text.overloaded arg = arg + 1 |Number.overloaded arg = arg + 2 |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 9b4d965f77fe..62a0ffa2cdec 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -725,6 +725,9 @@ class RuntimeSuggestionUpdatesTest val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" + // Note that Text.Text.overloaded is only to ensure that tests match expectations. + // In general Text.overloaded would also work because method resolution would assign it + // to the module rather than a type val contents = """from Standard.Base.Data.Number.Internal import Number |import Standard.Base.Data.Text @@ -736,7 +739,7 @@ class RuntimeSuggestionUpdatesTest | 10.overloaded x | Nothing | - |Text.overloaded arg = arg + 1 + |Text.Text.overloaded arg = arg + 1 |Number.overloaded arg = arg + 2 |""".stripMargin.linesIterator.mkString("\n") val version = contentsVersion(contents) From 9a703a348780fc9f225f821c20897a2d4bc65e2d Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 14:49:23 +0200 Subject: [PATCH 50/73] Update Changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f3ede14e62..16991ba5fdb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,6 +183,7 @@ - [Fixed compiler issue related to module cache.][3367] - [Fixed execution of defaulted arguments of Atom Constructors][3358] - [Converting Enso Date to java.time.LocalDate and back][3374] +- [Move Builtin Types and Methods definitions to stdlib][3363] [3227]: https://github.com/enso-org/enso/pull/3227 [3248]: https://github.com/enso-org/enso/pull/3248 @@ -192,6 +193,7 @@ [3360]: https://github.com/enso-org/enso/pull/3360 [3367]: https://github.com/enso-org/enso/pull/3367 [3374]: https://github.com/enso-org/enso/pull/3374 +[3363]: https://github.com/enso-org/enso/pull/3363 # Enso 2.0.0-alpha.18 (2021-10-12) From 2ddcf9fe6a2d622276e1740159d8484a4f8f491a Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 16:28:20 +0200 Subject: [PATCH 51/73] More docs for annotation processors --- .../dsl/BuiltinsMetadataProcessor.java | 67 +++++++++++++---- .../enso/interpreter/dsl/MethodProcessor.java | 41 +++++++--- .../enso/interpreter/dsl/TypeProcessor.java | 74 +++++++++++-------- 3 files changed, 127 insertions(+), 55 deletions(-) diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index 34ff2eb48846..79e8799a3838 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -13,15 +13,25 @@ import java.util.function.Function; import java.util.stream.Collectors; +/** + * The base class of Builtins processors. + * Apart from any associated with a given annotation, such as generating code, + * {@code BuiltinsMetadataProcessor} detects when the processing of the last annotation in the round + * is being processed and allows for dumping any collected metadata once. + */ public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { - protected abstract String metadataPath(); - - protected abstract void cleanup(); - - protected abstract void storeMetadata(Writer writer, Map pastEntries) - throws IOException; - + /** + * Processes annotated elements, generating code for each of them, if necessary. + * + * Compared to regular annotations processor, it will detect the last round of processing, + * read any existing metadata (for diff to handle separate compilation) and call + * @{code storeMetadata} to dump any metadata, if needed. + * + * @param annotations annotation being processed this round. + * @param roundEnv additional round information. + * @return {@code true} + */ @Override public final boolean process(Set annotations, RoundEnvironment roundEnv) { if (roundEnv.errorRaised()) { @@ -29,14 +39,17 @@ public final boolean process(Set annotations, RoundEnviro } if (roundEnv.processingOver()) { // A hack to improve support for separate compilation. + // // Since one cannot open the existing resource file in Append mode, - // we read the whole file and provide to the function that does the update. - // Deletes/renaming is still not gonna work but that would be the same case + // we read the exisitng metadata. + // Deletes/renaming are still not going to work nicely but that would be the same case // if we were writing metadata information per source file anyway. Map pastEntries; try { FileObject existingFile = - processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); + processingEnv + .getFiler() + .getResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); try (InputStream resource = existingFile.openInputStream()) { pastEntries = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) @@ -44,6 +57,7 @@ public final boolean process(Set annotations, RoundEnviro .collect(Collectors.toMap(l -> l.split(":")[0], Function.identity())); } } catch (NoSuchFileException notFoundException) { + // This is the first time we are generating the metadata file, ignore the exception. pastEntries = new HashMap<>(); } catch (Exception e) { e.printStackTrace(); @@ -57,7 +71,7 @@ public final boolean process(Set annotations, RoundEnviro Writer writer = res.openWriter(); try { storeMetadata(writer, pastEntries); - // Separate compilation hack + // Dump past entries, to workaround separate compilation + annotation processing issues for (String value : pastEntries.values()) { writer.append(value + "\n"); } @@ -74,9 +88,29 @@ public final boolean process(Set annotations, RoundEnviro } } + /** - * The regular body of {@link #process}. Called during regular rounds if there are no outstanding - * errors. In the last round, one of the processors will dump all builtin metadata + * A name of the resource where metadata collected during the processing should be written to. + * + * @return a relative path to the resource file + */ + protected abstract String metadataPath(); + + /** + * The method called at the end of the round of annotation processing. It allows to write any + * collected metadata to a related resoource (see {@link BuiltinsMetadataProcessor#metadataPath()}). + * + * @param writer a writer to the metadata resource + * @param pastEntries entries from the previously created metadata file, if any. Entries that should + * not be appended to {@code writer} should be removed + * @throws IOException + */ + protected abstract void storeMetadata(Writer writer, Map pastEntries) + throws IOException; + + /** + * The main body of {@link #process} that needs to be implemented by the processors. + * The method is called during regular rounds if there are no outstanding errors. * * @param annotations as in {@link #process} * @param roundEnv as in {@link #process} @@ -84,4 +118,11 @@ public final boolean process(Set annotations, RoundEnviro */ protected abstract boolean handleProcess( Set annotations, RoundEnvironment roundEnv); + + /** + * Cleanup any metadata information collected during annotation processing. + * Called when all processing is done. + */ + protected abstract void cleanup(); + } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index d492d9017146..a0b89545e77d 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -17,7 +17,10 @@ import java.util.*; import java.util.stream.Collectors; -/** The processor used to generate code from the {@link BuiltinMethod} annotation. */ +/** + * The processor used to generate code from the {@link BuiltinMethod} annotation and collect + * metadata necessary for automatic builtin methods initialization. + */ @SupportedAnnotationTypes("org.enso.interpreter.dsl.BuiltinMethod") @SupportedSourceVersion(SourceVersion.RELEASE_11) @AutoService(Processor.class) @@ -27,6 +30,8 @@ public class MethodProcessor extends BuiltinsMetadataProcessor { /** * Processes annotated elements, generating code for each of them. + * The method also records information about builtin method in an internal map that + * will be dumped on the last round of processing. * * @param annotations annotation being processed this round. * @param roundEnv additional round information. @@ -87,17 +92,6 @@ public boolean handleProcess(Set annotations, RoundEnviro return true; } - protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { - for (Filer f : builtinMethods.keySet()) { - for (Map.Entry entry : builtinMethods.get(f).entrySet()) { - writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); - if (pastEntries.containsKey(entry.getKey())) { - pastEntries.remove(entry.getKey()); - } - } - } - } - private final List necessaryImports = Arrays.asList( "com.oracle.truffle.api.frame.VirtualFrame", @@ -419,6 +413,29 @@ private boolean generateWarningsCheck( } } + /** + * Dumps the information about the collected builtin methods to {@link MethodProcessor#metadataPath()} + * resource file. + * + * The format of a single row in the metadata file: + * : + * + * @param writer a writer to the metadata resource + * @param pastEntries entries from the previously created metadata file, if any. Entries that should + * not be appended to {@code writer} should be removed + * @throws IOException + */ + protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { + for (Filer f : builtinMethods.keySet()) { + for (Map.Entry entry : builtinMethods.get(f).entrySet()) { + writer.append(entry.getKey() + ":" + entry.getValue() + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); + } + } + } + } + protected void registerBuiltinMethod(Filer f, String name, String clazzName) { Map methods = builtinMethods.get(f); if (methods == null) { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 4644a0abe807..0676163e4af2 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -40,53 +40,55 @@ public String getParamNames() { public static final String META_PATH = "META-INF" + "/" + NODE_PKG.replace('.', '/') + "/BuiltinTypes.metadata"; - @Override - protected String metadataPath() { - return META_PATH; - } - - @Override - protected void cleanup() { - builtinTypes.clear(); - } - - @Override - protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { - for (Filer f : builtinTypes.keySet()) { - for (Map.Entry entry : builtinTypes.get(f).entrySet()) { - BuiltinTypeConstr constr = entry.getValue(); - writer.append( - entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); - if (pastEntries.containsKey(entry.getKey())) { - pastEntries.remove(entry.getKey()); - } - } - } - } - @Override protected boolean handleProcess( - Set annotations, RoundEnvironment roundEnv) { + Set annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); for (Element elt : annotatedElements) { TypeElement element = (TypeElement) elt; BuiltinType builtinTypeAnnotation = element.getAnnotation(BuiltinType.class); String pkgName = - processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); + processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); String clazzName = element.getSimpleName().toString(); // Replace CamelCase class name to Snake_Case used in Enso String ensoTypeName = clazzName.replaceAll("([^_A-Z])([A-Z])", "$1_$2"); registerBuiltinType( - processingEnv.getFiler(), - ensoTypeName, - pkgName + "." + clazzName, - builtinTypeAnnotation.params()); + processingEnv.getFiler(), + ensoTypeName, + pkgName + "." + clazzName, + builtinTypeAnnotation.params()); } } return true; } + /** + * Dumps the information about the collected builtin types to {@link MethodProcessor#metadataPath()} + * resource file. + * + * The format of a single row in the metadata file: + * ::[] + * + * @param writer a writer to the metadata resource + * @param pastEntries entries from the previously created metadata file, if any. Entries that should + * not be appended to {@code writer} should be removed + * @throws IOException + */ + @Override + protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { + for (Filer f : builtinTypes.keySet()) { + for (Map.Entry entry : builtinTypes.get(f).entrySet()) { + BuiltinTypeConstr constr = entry.getValue(); + writer.append( + entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); + } + } + } + } + protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { Map classes = builtinTypes.get(f); if (classes == null) { @@ -95,4 +97,16 @@ protected void registerBuiltinType(Filer f, String name, String clazzName, Strin } classes.put(name, new BuiltinTypeConstr(clazzName, params)); } + + + @Override + protected String metadataPath() { + return META_PATH; + } + + @Override + protected void cleanup() { + builtinTypes.clear(); + } + } From c927582f32117481bcac7d903378b6406f6a89cd Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Mon, 25 Apr 2022 17:10:20 +0200 Subject: [PATCH 52/73] More Standard.Builtins purge --- app/gui/src/controller/searcher/action/hardcoded.rs | 10 +++++----- .../org/enso/interpreter/runtime/type/Constants.java | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/gui/src/controller/searcher/action/hardcoded.rs b/app/gui/src/controller/searcher/action/hardcoded.rs index 609f2740ac1f..20341d8f2956 100644 --- a/app/gui/src/controller/searcher/action/hardcoded.rs +++ b/app/gui/src/controller/searcher/action/hardcoded.rs @@ -197,11 +197,11 @@ thread_local! { suggestions : vec![ Rc::new( Suggestion::new("Text Input","\"\"",&icons.text_input) - .with_return_type("Standard.Builtins.Main.Text") + .with_return_type("Standard.Base.Data.Text.Text") ), Rc::new( Suggestion::new("Number Input","0",&icons.number_input) - .with_return_type("Standard.Builtins.Main.Number") + .with_return_type("Standard.Base.Data.Number.Internal.Number") ), ] }, @@ -211,8 +211,8 @@ thread_local! { suggestions : vec![ Rc::new( Suggestion::new("Text Length","length",&icons.default) - .with_this_arg("Standard.Builtins.Main.Text") - .with_return_type("Standard.Base.Main.Integer") + .with_this_arg("Standard.Base.Data.Text.Text") + .with_return_type("Standard.Base.Data.Number.Internal.Integer") .marked_as_method_call("length","Standard.Base.Data.Text.Extensions") ) ] @@ -231,7 +231,7 @@ thread_local! { Suggestion::new("Fetch Data", "Http.fetch",&icons.default) .with_return_type("Standard.Base.Network.Http.Body.Body") .with_argument_types(vec![ - "Standard.Builtins.Main.Text", + "Standard.Base.Data.Text.Text", "Vector.Vector", ]) .with_import_added("Standard.Base.Network.Http") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 486e72d22b91..7fc8a377435e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -1,6 +1,6 @@ package org.enso.interpreter.runtime.type; -/** Types defined in the Standard.Builtins module. */ +/** Hard-coded names of builtins. */ public class Constants { public static final String ANY = "Standard.Base.Data.Any.Any"; @@ -11,12 +11,14 @@ public class Constants { public static final String FUNCTION = "Standard.Base.Function.Function"; public static final String INTEGER = "Standard.Base.Data.Number.Internal.Integer"; public static final String MANAGED_RESOURCE = "Standard.Base.Runtime.Resource.Managed_Resource"; - public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; public static final String NOTHING = "Standard.Base.Nothing.Nothing"; public static final String NUMBER = "Standard.Base.Data.Number.Internal.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; public static final String TEXT = "Standard.Base.Data.Text.Text"; + + // Remaining constants that are not Builtins but refer to builtin-related internals + public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; } From 1ecd3176c9753b40d121ceebea0579bfdb97ce05 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 15:39:52 +0200 Subject: [PATCH 53/73] Follow up on merge with develop --- .../Standard/Base/0.0.0-dev/src/Function.enso | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso index f07bc5316291..4a478a005f84 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso @@ -7,20 +7,3 @@ type Function the this argument. @Builtin_Type type Function - - ## Forces evaluation of a fully-applied but not evaluated function. - - This is particularly useful when you want to call a function that is - fully applied with default arguments. - - This is usually _not_ the correct solution to a problem, and so should be - used sparingly. - - > Example - Evaluate a fully applied function to get 4. - - example_call = - f (a = 2) = a * a - f.call - call : Any - call = @Builtin_Method "Function.call" From a384ed0164b85acc3ca440a3ac66acd44e95d803 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 15:52:31 +0200 Subject: [PATCH 54/73] PR review re IO and Prim_Io modules Got rid of IO type and moved Prim_Io methods to File module. --- .../lib/Standard/Base/0.0.0-dev/src/IO.enso | 6 +--- .../Base/0.0.0-dev/src/IO/Prim_Io.enso | 29 ------------------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 -- .../Base/0.0.0-dev/src/System/File.enso | 28 ++++++++++++++++-- .../expression/builtin/io/GetCwdNode.java | 2 +- .../expression/builtin/io/GetFileNode.java | 2 +- .../builtin/io/GetUserHomeNode.java | 2 +- 7 files changed, 29 insertions(+), 42 deletions(-) delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso index 4313fcb0c937..24b01bd0ba29 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso @@ -1,8 +1,4 @@ -## Built in IO operations. -type IO - - ## A type containing basic operations for performing input and output. - type IO +## Builtin IO operations. ## Prints the provided message to standard error. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso deleted file mode 100644 index f15591d56b76..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/IO/Prim_Io.enso +++ /dev/null @@ -1,29 +0,0 @@ -## Primitive IO operations internal to the runtime. -type Prim_Io - - ## PRIVATE - - A type for primitive IO operations. - type Prim_Io - -## PRIVATE - - Gets a file corresponding to the current working directory of the - program. -get_cwd : File -get_cwd = @Builtin_Method "Prim_Io.get_cwd" - -## PRIVATE - - Gets a file corresponding to the provided path. - - Arguments: - - path: The path to obtain a file at. -get_file : Text -> File -get_file path = @Builtin_Method "Prim_Io.get_file" - -## PRIVATE - - Gets the textual path to the user's system-defined home directory. -user_home : Text -user_home = @Builtin_Method "Prim_Io.user_home" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 387fa2acf9e8..9244a3b34c69 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -20,7 +20,6 @@ import project.Data.Text.Matching import project.Data.Vector import project.Error.Common import project.Function -import project.IO.Prim_Io import project.IO import project.Nothing import project.Math @@ -47,7 +46,6 @@ export project.Data.Ordering.Sort_Order export project.Data.Ref export project.Data.Vector export project.IO -export project.IO.Prim_Io export project.Math export project.Meta export project.Polyglot.Java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso index 83673d1f876d..e4e7aa7cbea5 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso @@ -33,7 +33,7 @@ polyglot java import java.nio.file.Path example_new = File.new Examples.csv_path new : (Text | File) -> File new path = case path of - Text -> File (Prim_Io.get_file path) + Text -> File (here.get_file path) _ -> path ## Open and reads all bytes in the file at the provided `path` into a byte vector. @@ -130,7 +130,7 @@ write_text path contents (encoding=Encoding.utf_8) = example_cwd = File.current_directory current_directory : File -current_directory = File (Prim_Io.get_cwd) +current_directory = File (here.get_cwd) ## ALIAS Home Directory @@ -143,7 +143,7 @@ current_directory = File (Prim_Io.get_cwd) example_home = File.home home : File -home = here.new (Prim_Io.get_user_home) +home = here.new (here.get_user_home) ## Lists files contained in the provided directory. @@ -947,3 +947,25 @@ list_descendants file = False -> Nothing go file builder.to_vector + +## PRIVATE + + Gets a file corresponding to the current working directory of the + program. +get_cwd : File +get_cwd = @Builtin_Method "File.get_cwd" + +## PRIVATE + + Gets a file corresponding to the provided path. + + Arguments: + - path: The path to obtain a file at. +get_file : Text -> File +get_file path = @Builtin_Method "File.get_file" + +## PRIVATE + + Gets the textual path to the user's system-defined home directory. +user_home : Text +user_home = @Builtin_Method "File.user_home" diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java index 1061c38a5c19..0cbb8c53d653 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java @@ -8,7 +8,7 @@ import org.enso.interpreter.runtime.data.EnsoFile; @BuiltinMethod( - type = "Prim_Io", + type = "File", name = "get_cwd", description = "A file corresponding to the current working directory.") public abstract class GetCwdNode extends Node { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java index be7d72e64080..d70c5cd4e786 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetFileNode.java @@ -10,7 +10,7 @@ import org.enso.interpreter.runtime.data.EnsoFile; @BuiltinMethod( - type = "Prim_Io", + type = "File", name = "get_file", description = "Takes the text representation of a path and returns a TruffleFile corresponding to it.") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetUserHomeNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetUserHomeNode.java index 5535c2f78bfb..d56b7ae6918e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetUserHomeNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetUserHomeNode.java @@ -5,7 +5,7 @@ import org.enso.interpreter.runtime.data.text.Text; @BuiltinMethod( - type = "Prim_Io", + type = "File", name = "user_home", description = "Get the text path to the user home directory.") public final class GetUserHomeNode extends Node { From 40ad2c765c1b8913b04509783eb225880d891ff0 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 16:31:52 +0200 Subject: [PATCH 55/73] PR review Numbers Moved Data.Number.Internal to Data.Numbers. Ideally that would be distributed nicely to modules like Number.enso Number/Integer.enso etc but due to name ambiguity of types with the same name as the module this would be a bit annoying now. --- .../controller/searcher/action/hardcoded.rs | 4 +- .../0.0.0-dev/src/Data/Json/Internal.enso | 2 +- .../Base/0.0.0-dev/src/Data/List.enso | 2 +- .../{Number/Internal.enso => Numbers.enso} | 8 +--- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 4 +- .../0.0.0-dev/src/Sql/Visualization.enso | 4 +- .../fixtures/semantic/AtomFixtures.scala | 2 +- .../fixtures/semantic/CallableFixtures.scala | 2 +- .../fixtures/semantic/RecursionFixtures.scala | 4 +- .../interpreter/runtime/type/Constants.java | 6 +-- .../test/instrument/ReplTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 46 +++++++++---------- .../RuntimeSuggestionUpdatesTest.scala | 4 +- .../RuntimeVisualisationsTest.scala | 12 ++--- .../test/semantic/InteropTest.scala | 2 +- .../semantic/LambdaShorthandArgsTest.scala | 4 +- .../test/semantic/LambdaTest.scala | 2 +- .../interpreter/test/semantic/StateTest.scala | 10 ++-- test/Tests/src/Data/Numbers_Spec.enso | 2 +- test/Tests/src/Semantic/Meta_Spec.enso | 2 +- test/Visualization_Tests/src/Sql_Spec.enso | 2 +- 21 files changed, 60 insertions(+), 66 deletions(-) rename distribution/lib/Standard/Base/0.0.0-dev/src/Data/{Number/Internal.enso => Numbers.enso} (99%) diff --git a/app/gui/src/controller/searcher/action/hardcoded.rs b/app/gui/src/controller/searcher/action/hardcoded.rs index 20341d8f2956..83d28c0608fa 100644 --- a/app/gui/src/controller/searcher/action/hardcoded.rs +++ b/app/gui/src/controller/searcher/action/hardcoded.rs @@ -201,7 +201,7 @@ thread_local! { ), Rc::new( Suggestion::new("Number Input","0",&icons.number_input) - .with_return_type("Standard.Base.Data.Number.Internal.Number") + .with_return_type("Standard.Base.Data.Numbers.Number") ), ] }, @@ -212,7 +212,7 @@ thread_local! { Rc::new( Suggestion::new("Text Length","length",&icons.default) .with_this_arg("Standard.Base.Data.Text.Text") - .with_return_type("Standard.Base.Data.Number.Internal.Integer") + .with_return_type("Standard.Base.Data.Numbers.Integer") .marked_as_method_call("length","Standard.Base.Data.Text.Extensions") ) ] diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso index 2c5357ce3470..8371072db695 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json/Internal.enso @@ -1,6 +1,6 @@ from Standard.Base import all hiding Number, Boolean, Array -import Standard.Base.Data.Number.Internal as Base_Number +import Standard.Base.Data.Numbers as Base_Number from Standard.Base.Data.Json import all diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index ba97fb041189..f9d485aeafd2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,4 +1,4 @@ -from Standard.Base.Data.Number.Internal import all +from Standard.Base.Data.Numbers import all from Standard.Base.Error.Common import Error from Standard.Base.Data.Boolean import True, False import Standard.Base.Nothing diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso similarity index 99% rename from distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso rename to distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso index 204dcdbb3e8e..f235e6902990 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Internal.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso @@ -8,6 +8,7 @@ import Standard.Base.Data.Json from Standard.Base.Data.Boolean import all from Standard.Base.Data.Range import all from Standard.Base.Error.Common import Panic,Error,Illegal_Argument_Error + ## The root type of the Enso numeric hierarchy. If a Number is expected, then the program can provide either a Decimal or @@ -363,11 +364,7 @@ type Number if this < 0 then -1 else 0 -################### -## Decimal -################### ## Decimal numbers. - type Decimal ## Decimal is the type of decimal numbers in Enso. @@ -612,9 +609,6 @@ type Decimal Panic.catch NumberFormatException (Double.parseDouble text) _-> Error.throw (Parse_Error text) -################ -## Integer -################ ## Integral numbers. type Integer diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index 9244a3b34c69..8e4f5232f5b7 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso @@ -8,7 +8,7 @@ import project.Data.Locale import project.Data.Map import project.Data.Maybe import project.Data.Noise -import project.Data.Number.Internal +import project.Data.Numbers import project.Data.Ordering import project.Data.Ordering.Sort_Order import project.Data.Pair @@ -60,7 +60,7 @@ from project.Data.Array export Array from project.Data.Any export all from project.Data.Boolean export all from project.Data.List export Nil, Cons, List -from project.Data.Number.Internal export all hiding Math, String, Double, Parse_Error +from project.Data.Numbers export all hiding Math, String, Double, Parse_Error from project.Data.Noise export all hiding Noise from project.Data.Pair export Pair from project.Data.Range export all diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso index 40240452ca36..abe463985357 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Sql/Visualization.enso @@ -40,8 +40,8 @@ prepare_visualization x = Helpers.recover_errors <| types it will return `Nothing`. find_expected_enso_type_for_sql : Sql_Type -> Text find_expected_enso_type_for_sql sql_type = - if sql_type.is_definitely_integer then "Standard.Base.Data.Number.Internal.Integer" else - if sql_type.is_definitely_double then "Standard.Base.Data.Number.Internal.Decimal" else + if sql_type.is_definitely_integer then "Standard.Base.Data.Numbers.Integer" else + if sql_type.is_definitely_double then "Standard.Base.Data.Numbers.Decimal" else if sql_type.is_definitely_text then "Standard.Base.Data.Text.Text" else if sql_type.is_definitely_boolean then "Standard.Base.Boolean.Boolean" else Nothing diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 6b8d5b744774..ddb3c245ffc3 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -7,7 +7,7 @@ class AtomFixtures extends DefaultInterpreterRunner { val millionElementList = eval( s"""|from Standard.Base.Data.List import Cons,Nil - |from Standard.Base.Data.Number.Internal import all + |from Standard.Base.Data.Numbers import all | |main = | res = (1.up_to $million).fold Nil (acc -> x -> Cons x acc) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala index 494b88f79833..38c392d91c02 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/CallableFixtures.scala @@ -7,7 +7,7 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOfromCallCode = """ - |from Standard.Base.Data.Number.Internal import all + |from Standard.Base.Data.Numbers import all | |type Foo | diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala index 74a034f51851..1337acd009c8 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/RecursionFixtures.scala @@ -49,7 +49,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val oversaturatedRecursiveCall = getMain(oversaturatedRecursiveCallTCOCode) val sumStateTCOCode = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.Runtime.State | |stateSum = n -> @@ -76,7 +76,7 @@ class RecursionFixtures extends DefaultInterpreterRunner { val sumTCOWithEval = getMain(sumTCOWithEvalCode) val nestedThunkSumCode = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.Runtime.State |import Standard.Base.Nothing | diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 7fc8a377435e..81077d28b07f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -6,13 +6,13 @@ public class Constants { public static final String ANY = "Standard.Base.Data.Any.Any"; public static final String ARRAY = "Standard.Base.Data.Array.Array"; public static final String BOOLEAN = "Standard.Base.Data.Boolean.Boolean"; - public static final String DECIMAL = "Standard.Base.Data.Number.Internal.Decimal"; + public static final String DECIMAL = "Standard.Base.Data.Numbers.Decimal"; public static final String ERROR = "Standard.Base.Error.Common.Error"; public static final String FUNCTION = "Standard.Base.Function.Function"; - public static final String INTEGER = "Standard.Base.Data.Number.Internal.Integer"; + public static final String INTEGER = "Standard.Base.Data.Numbers.Integer"; public static final String MANAGED_RESOURCE = "Standard.Base.Runtime.Resource.Managed_Resource"; public static final String NOTHING = "Standard.Base.Nothing.Nothing"; - public static final String NUMBER = "Standard.Base.Data.Number.Internal.Number"; + public static final String NUMBER = "Standard.Base.Data.Numbers.Number"; public static final String PANIC = "Standard.Base.Error.Common.Panic"; public static final String REF = "Standard.Base.Data.Ref.Ref"; public static final String TEXT = "Standard.Base.Data.Text.Text"; diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 3bade5c99b46..1a63dab66885 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -153,7 +153,7 @@ class ReplTest """ |import Standard.Base.Runtime.Debug |import Standard.Base.Runtime.State - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |run = | State.put Number 10 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index c395d564a354..aa50c980d61f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -119,7 +119,7 @@ class RuntimeServerTest def code = metadata.appendToCode( """ - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |main = | x = 6 @@ -728,11 +728,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(121, 41) - val idMainBar = metadata.addItem(153, 8) + val idMain = metadata.addItem(113, 41) + val idMainBar = metadata.addItem(145, 8) val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.IO |import Standard.Base.Runtime.State | @@ -789,11 +789,11 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(121, 40) - val idMainBar = metadata.addItem(152, 8) + val idMain = metadata.addItem(113, 40) + val idMainBar = metadata.addItem(144, 8) val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.IO |import Standard.Base.Runtime.State | @@ -1174,19 +1174,19 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(85, 35) - val idMainA = metadata.addItem(94, 8) - val idMainP = metadata.addItem(107, 12) + val idMain = metadata.addItem(77, 35) + val idMainA = metadata.addItem(86, 8) + val idMainP = metadata.addItem(99, 12) // pie id - metadata.addItem(127, 1) + metadata.addItem(119, 1) // uwu id - metadata.addItem(135, 1) + metadata.addItem(127, 1) // hie id - metadata.addItem(143, 6) + metadata.addItem(135, 6) // Number.x id - metadata.addItem(163, 1) + metadata.addItem(155, 1) val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.IO | |main = @@ -1380,16 +1380,16 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(130, 88) - val id1 = metadata.addItem(139, 15) - val id2 = metadata.addItem(159, 18) - val id3 = metadata.addItem(182, 15) + val idMain = metadata.addItem(122, 88) + val id1 = metadata.addItem(131, 15) + val id2 = metadata.addItem(151, 18) + val id3 = metadata.addItem(174, 15) // Note that Nothing.Nothing is on purpose. // If not provided the full name it will resolve the expression Nothing to a Nothing module. // Similarly Text.Text. That in turn will mismatch the expectations for method types which actually // return proper types. val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |from Standard.Base.Data.Text import all |import Standard.Base.Nothing | @@ -1844,7 +1844,7 @@ class RuntimeServerTest ) val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.IO | |main = IO.println "I'm a file!" @@ -1881,7 +1881,7 @@ class RuntimeServerTest /* Modify the file: - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.IO | |Number.lucky = 42 @@ -2443,7 +2443,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number | |main = Number.pi |""".stripMargin.linesIterator.mkString("\n") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 62a0ffa2cdec..f4a62269a23f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -729,7 +729,7 @@ class RuntimeSuggestionUpdatesTest // In general Text.overloaded would also work because method resolution would assign it // to the module rather than a type val contents = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |import Standard.Base.Data.Text |import Standard.Base.Nothing | @@ -912,7 +912,7 @@ class RuntimeSuggestionUpdatesTest |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") val aCode = - """from Standard.Base.Data.Number.Internal import Integer + """from Standard.Base.Data.Numbers import Integer | |type MyType | type MkA a diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index fa40ea7d1495..adfab4bde244 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -109,16 +109,16 @@ class RuntimeVisualisationsTest val metadata = new Metadata - val idMainX = metadata.addItem(71, 1) - val idMainY = metadata.addItem(81, 7) - val idMainZ = metadata.addItem(97, 5) - val idFooY = metadata.addItem(136, 8) - val idFooZ = metadata.addItem(153, 5) + val idMainX = metadata.addItem(63, 1) + val idMainY = metadata.addItem(83, 7) + val idMainZ = metadata.addItem(89, 5) + val idFooY = metadata.addItem(128, 8) + val idFooZ = metadata.addItem(145, 5) def code = metadata.appendToCode( """ - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |main = | x = 6 diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 44bdaa7c1faa..e02a6eb2aba7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -57,7 +57,7 @@ class InteropTest extends InterpreterTest { "work with unresolved symbols" in { val code = - """from Standard.Base.Data.Number.Internal import all + """from Standard.Base.Data.Numbers import all |from Standard.Base.Data.Text import all | |Number.add x = x + this diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala index 57ee279230d9..52650c9ead02 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala @@ -50,7 +50,7 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work with mixfix functions" in { val code = - """from Standard.Base.Data.Number.Internal import all + """from Standard.Base.Data.Numbers import all | |Number.if_then_else = ~t -> ~f -> if this == 0 then t else f | @@ -142,7 +142,7 @@ class LambdaShorthandArgsTest extends InterpreterTest { "work properly when used with dot notation" in { val code = """ - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |Number.f = this + 10 | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index 855a1d7acee3..d9c1a0ca3ffa 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -134,7 +134,7 @@ class LambdaTest extends InterpreterTest { "call fully saturated lambdas returned with TCO" in { val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number | |Number.if_then_else = ~t -> ~f -> if this == 0 then t else f | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index 308bf9f8710c..571752854b69 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -12,7 +12,7 @@ class StateTest extends InterpreterTest { "be accessible from functions" in { val code = """import Standard.Base.Runtime.State - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |stateful = | State.put Number 10 @@ -29,7 +29,7 @@ class StateTest extends InterpreterTest { "be implicitly threaded through function executions" in { val code = """import Standard.Base.Runtime.State - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |inc_state = | x = State.get Number @@ -52,7 +52,7 @@ class StateTest extends InterpreterTest { "work well with recursive code" in { val code = """import Standard.Base.Runtime.State - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |main = | stateSum = n -> @@ -67,7 +67,7 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Base.Data.Number.Internal import Number + """from Standard.Base.Data.Numbers import Number |from Standard.Base.Data.List import Nil |import Standard.Base.IO |import Standard.Base.Nothing @@ -117,7 +117,7 @@ class StateTest extends InterpreterTest { "localize properly with State.run when 1 key used" in { val code = """import Standard.Base.Runtime.State - |from Standard.Base.Data.Number.Internal import Number + |from Standard.Base.Data.Numbers import Number | |inner = State.put Number 0 | diff --git a/test/Tests/src/Data/Numbers_Spec.enso b/test/Tests/src/Data/Numbers_Spec.enso index 340a8e398f25..350aa38b11dc 100644 --- a/test/Tests/src/Data/Numbers_Spec.enso +++ b/test/Tests/src/Data/Numbers_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Number.Internal import Parse_Error +from Standard.Base.Data.Numbers import Parse_Error import Standard.Test diff --git a/test/Tests/src/Semantic/Meta_Spec.enso b/test/Tests/src/Semantic/Meta_Spec.enso index f9c913223239..a12aba76a313 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -87,7 +87,7 @@ spec = Test.group "Meta-Value Manipulation" <| Test.specify "should allow to get qualified type names of values" <| x = 42 y = My_Type 1 2 3 - Meta.get_qualified_type_name x . should_equal "Standard.Base.Data.Number.Internal.Integer" + Meta.get_qualified_type_name x . should_equal "Standard.Base.Data.Numbers.Integer" Meta.get_qualified_type_name y . should_equal "enso_dev.Tests.Semantic.Meta_Spec.My_Type" Test.specify "should allow access to package names" <| diff --git a/test/Visualization_Tests/src/Sql_Spec.enso b/test/Visualization_Tests/src/Sql_Spec.enso index 276a2c5bee7b..05acc12c16b6 100644 --- a/test/Visualization_Tests/src/Sql_Spec.enso +++ b/test/Visualization_Tests/src/Sql_Spec.enso @@ -11,7 +11,7 @@ visualization_spec connection = Test.specify "should provide type metadata for interpolations" <| q = t.where ((t.at "B" == 2) && (t.at "A" == True)) . at "C" vis = Visualization.prepare_visualization q - int_param = Json.from_pairs [["value", 2], ["actual_type", "Standard.Base.Data.Number.Internal.Integer"], ["expected_sql_type", "INTEGER"], ["expected_enso_type", "Standard.Base.Data.Number.Internal.Integer"]] + int_param = Json.from_pairs [["value", 2], ["actual_type", "Standard.Base.Data.Numbers.Integer"], ["expected_sql_type", "INTEGER"], ["expected_enso_type", "Standard.Base.Data.Numbers.Integer"]] str_param = Json.from_pairs [["value", True], ["actual_type", "Standard.Base.Data.Boolean.Boolean"], ["expected_sql_type", "VARCHAR"], ["expected_enso_type", "Standard.Base.Data.Text.Text"]] code = 'SELECT "T"."C" AS "C" FROM "T" AS "T" WHERE (("T"."B" = ?) AND ("T"."A" = ?))' json = Json.from_pairs [["dialect", "sqlite"], ["code", code], ["interpolations", [int_param, str_param]]] From 23e9298bad5af63c44b649b5073e8a88579e0b50 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 16:44:54 +0200 Subject: [PATCH 56/73] Remove builtin Ordering type It wasn't necessary, it is still being defined internally however. --- .../lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso | 6 ------ 1 file changed, 6 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso index f2622d904168..e575cce423c9 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso @@ -20,12 +20,6 @@ from_sign sign = if sign == 0 then Equal else `that`. So, if `this` is greater than `that`, you should return `Greater.` type Ordering - ## A representation of the relative ordering between two values. - - These values must be able to be ordered with respect to each other. - @Builtin_Type - type Ordering - ## A representation that the first value orders as less than the second. @Builtin_Type type Less From a33b45d8a209752ff9168bf5bef0b90a7f403426 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 16:50:33 +0200 Subject: [PATCH 57/73] Move FIXME comment on Ref to pivotal ticket --- distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso index 3a33e7fa294b..f9c66d07131e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso @@ -5,8 +5,6 @@ type Ref @Builtin_Type type Ref -## FIXME consider moving this as methods of Ref, currently a lot of stuff depends -## on the current design ## Gets the contents of the mutable reference ref. Arguments: @@ -42,4 +40,4 @@ put ref new_value = @Builtin_Method "Ref.put" Ref.new 7 new : Any -> Ref -new value = @Builtin_Method "Ref.new" \ No newline at end of file +new value = @Builtin_Method "Ref.new" From 0c5c19cca51605a063c492fc57101616bf6206f8 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 16:53:14 +0200 Subject: [PATCH 58/73] Remove leftover comment --- distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso index 1acf3cc05f96..529f07434cd6 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -4,12 +4,6 @@ import Standard.Base.Nothing from Standard.Base.Runtime.Extensions import Source_Location ## Utilities for interacting with the runtime. -##type Runtime -## -## ## A container type for utility methods that allow interacting with the Enso -## runtime. -## @Builtin_Type -## type Runtime ## PRIVATE @@ -95,4 +89,4 @@ wrap_primitive_stack_trace_element el = Represents a single stack frame in an Enso stack trace. type Stack_Trace_Element ## PRIVATE - type Stack_Trace_Element name source_location \ No newline at end of file + type Stack_Trace_Element name source_location From 3417b66985b1b1c3e57c7e3ae654677a040a0e8d Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 22:50:37 +0200 Subject: [PATCH 59/73] More cleanups, as per PR comments --- build.sbt | 5 ++++- .../Standard/Base/0.0.0-dev/src/Runtime/Debug.enso | 3 --- .../Base/0.0.0-dev/src/Runtime/Resource.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Warning.enso | 2 +- .../expression/builtin/error/ArithmeticError.java | 2 +- .../node/expression/builtin/error/ArityError.java | 2 +- .../node/expression/builtin/error/CaughtPanic.java | 2 +- .../node/expression/builtin/error/CompileError.java | 2 +- .../error/InexhaustivePatternMatchError.java | 2 +- .../builtin/error/InvalidArrayIndexError.java | 2 +- .../builtin/error/InvalidConversionTargetError.java | 2 +- .../builtin/error/ModuleDoesNotExist.java | 2 +- .../builtin/error/NoSuchConversionError.java | 2 +- .../expression/builtin/error/NoSuchMethodError.java | 2 +- .../expression/builtin/error/NotInvokableError.java | 2 +- .../expression/builtin/error/PolyglotError.java | 2 +- .../node/expression/builtin/error/SyntaxError.java | 2 +- .../node/expression/builtin/error/TypeError.java | 2 +- .../builtin/error/UninitializedState.java | 2 +- .../builtin/error/UnsupportedArgumentTypes.java | 2 +- .../expression/builtin/meta/ProjectDescription.java | 2 +- .../builtin/system/SystemProcessResult.java | 2 +- .../enso/interpreter/runtime/scope/ModuleScope.java | 8 +++----- .../org/enso/compiler/codegen/IrToTruffle.scala | 6 ++++++ .../enso/compiler/pass/desugar/ComplexType.scala | 4 ---- .../java/org/enso/interpreter/dsl/BuiltinType.java | 4 ++-- .../org/enso/interpreter/dsl/TypeProcessor.java | 13 ++++++++----- 27 files changed, 43 insertions(+), 40 deletions(-) diff --git a/build.sbt b/build.sbt index 92e090648f44..42638b1ce09f 100644 --- a/build.sbt +++ b/build.sbt @@ -952,7 +952,10 @@ lazy val searcher = project lazy val `interpreter-dsl` = (project in file("lib/scala/interpreter-dsl")) .settings( version := "0.1", - libraryDependencies += "com.google.auto.service" % "auto-service" % "1.0.1" exclude ("com.google.code.findbugs", "jsr305") + libraryDependencies ++= Seq( + "org.apache.commons" % "commons-lang3" % commonsLangVersion, + "com.google.auto.service" % "auto-service" % "1.0.1" exclude ("com.google.code.findbugs", "jsr305") + ) ) // ============================================================================ diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso index dedfa332b1c3..473b06f5a1ef 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso @@ -1,7 +1,4 @@ ## Debug utilities. -## A type on which debugging functionality is exposed. -@Builtin_Type -type Debug ## TEXT_ONLY diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso index 6cceb0ad8ac7..b7db4c23f562 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso @@ -74,4 +74,4 @@ type Managed_Resource - resource: The managed resource from which to acquire the underlying resource. take : Managed_Resource -> Any - take resource = @Builtin_Method "Managed_Resource.take" \ No newline at end of file + take resource = @Builtin_Method "Managed_Resource.take" diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso index 8cac048fb0a9..87cec6e1a27d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Warning.enso @@ -191,9 +191,9 @@ merge_matched_warnings value matcher merger = Warning.attach warning acc ## PRIVATE - type Prim_Warning + ## PRIVATE type Prim_Warning ## PRIVATE diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java index 51f07586adbd..34e56329520d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "message") +@BuiltinType(params = {"message"}) public class ArithmeticError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java index 9491476e24eb..ed01ba120d72 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "expected_min,expected_max,actual") +@BuiltinType(params = {"expected_min","expected_max","actual"}) public class ArityError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 03dd4939a4ed..67075c279250 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "payload,internal_original_exception") +@BuiltinType(params = {"payload","internal_original_exception"}) public class CaughtPanic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java index 16b001cfd853..d1a1a2092b00 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "message") +@BuiltinType(params = {"message"}) public class CompileError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java index ee9c449e2488..78cad5219e70 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "scrutinee") +@BuiltinType(params = {"scrutinee"}) public class InexhaustivePatternMatchError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java index edca9f1e3508..89a8e39b2ecd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "array,index") +@BuiltinType(params = {"array","index"}) public class InvalidArrayIndexError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java index ae967c1f1881..231b5eec4e5b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "target") +@BuiltinType(params = {"target"}) public class InvalidConversionTargetError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java index f10c4c4ece2a..5c5b372e9437 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "name") +@BuiltinType(params = {"name"}) public class ModuleDoesNotExist extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java index da0c7aacfc0c..941abba73bf2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "target,that,conversion") +@BuiltinType(params = {"target","that","conversion"}) public class NoSuchConversionError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java index 1d1d420863f0..ab15090c8460 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "target,symbol") +@BuiltinType(params = {"target","symbol"}) public class NoSuchMethodError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java index 40d2fe30fbee..cf93a27632a2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "target") +@BuiltinType(params = {"target"}) public class NotInvokableError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java index de651770ce08..afedbf4da69d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "cause") +@BuiltinType(params = {"cause"}) public class PolyglotError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java index c94531789d4b..d097110a9583 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "message") +@BuiltinType(params = {"message"}) public class SyntaxError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java index e8a59ba758f2..7c657eaf5999 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "expected,actual,name") +@BuiltinType(params = {"expected","actual","name"}) public class TypeError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java index 91a41a90aca9..43c08797f6ed 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "key") +@BuiltinType(params = {"key"}) public class UninitializedState extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java index bd8bde436a43..49c6e118a38d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "arguments") +@BuiltinType(params = {"arguments"}) public class UnsupportedArgumentTypes extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java index e06ed836f839..0549a4360ed3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "prim_root_file,prim_config") +@BuiltinType(params = {"prim_root_file","prim_config"}) public class ProjectDescription extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java index 599872cb26be..96d22f648e2b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = "exit_code,stdout,stderr") +@BuiltinType(params = {"exit_code","stdout","stderr"}) public class SystemProcessResult extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 4be7e5f43bcf..09b66083d1cc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -115,11 +115,9 @@ public void registerMethod(AtomConstructor atom, String method, Function functio Map methodMap = ensureMethodMapFor(atom); if (methodMap.containsKey(method)) { - if (!atom.isBuiltin()) { - // Builtin types will have double definition because of - // BuiltinMethod and that's OK - throw new RedefinedMethodException(atom.getName(), method); - } + // Builtin types will have double definition because of + // BuiltinMethod and that's OK + throw new RedefinedMethodException(atom.getName(), method); } else { methodMap.put(method, function); } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index e1cb67d0975c..b3a8d801a344 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -293,6 +293,11 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => + // For builtin types that own the builtin method we only check that + // the method has been registered during the initialization of builtins + // and not attempt to register it in the scope (can't redefined methods). + // For non-builtin types (or modules) that own the builtin method + // we have to look up the function and register it in the scope. val builtinFunction = context.getBuiltins .getBuiltinFunction(cons, methodDef.methodName.name, language) builtinFunction.toScala @@ -311,6 +316,7 @@ class IrToTruffle( ) Right(None) else Left(l) ) + .map(_.filterNot(_ => cons.isBuiltin)) case fn: IR.Function => val (body, arguments) = expressionProcessor.buildFunctionBody(fn.arguments, fn.body) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala index b6726e9986d4..55c624c845b2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala @@ -115,10 +115,6 @@ case object ComplexType extends IRPass { .map(atom => annotations .map(ann => { - - // Annotations of Atoms in Complex Types were being overwritten. We want to make sure that - // we only append the annotations of complex types without errasing the former. - // FIXME check if there is a nicer way of doing this val old = atom .getMetadata(ModuleAnnotations) .map(_.annotations) diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java index 9e878135e300..d0306337067c 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -9,11 +9,11 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface BuiltinType { + /** * Comma-separated list of parameters of builting type * * @return list of params */ - // FIXME: - String params() default ""; + String[] params() default {}; } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 0676163e4af2..6f6421b541aa 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -8,10 +8,13 @@ import javax.lang.model.element.TypeElement; import java.io.IOException; import java.io.Writer; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.apache.commons.lang3.StringUtils; + @SupportedAnnotationTypes("org.enso.interpreter.dsl.BuiltinType") @SupportedSourceVersion(SourceVersion.RELEASE_11) @AutoService(Processor.class) @@ -20,9 +23,9 @@ public class TypeProcessor extends BuiltinsMetadataProcessor { private class BuiltinTypeConstr { private String tpeName; - private String paramNames; + private String[] paramNames; - BuiltinTypeConstr(String tpeName, String params) { + BuiltinTypeConstr(String tpeName, String[] params) { this.tpeName = tpeName; this.paramNames = params; } @@ -31,7 +34,7 @@ public String getTpeName() { return tpeName; } - public String getParamNames() { + public String[] getParamNames() { return paramNames; } } @@ -81,7 +84,7 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr for (Map.Entry entry : builtinTypes.get(f).entrySet()) { BuiltinTypeConstr constr = entry.getValue(); writer.append( - entry.getKey() + ":" + constr.getTpeName() + ":" + constr.getParamNames() + "\n"); + entry.getKey() + ":" + constr.getTpeName() + ":" + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + "\n"); if (pastEntries.containsKey(entry.getKey())) { pastEntries.remove(entry.getKey()); } @@ -89,7 +92,7 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr } } - protected void registerBuiltinType(Filer f, String name, String clazzName, String params) { + protected void registerBuiltinType(Filer f, String name, String clazzName, String[] params) { Map classes = builtinTypes.get(f); if (classes == null) { classes = new HashMap<>(); From 7dc9a34498fe72f39a16799f7eeca682676f815b Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 28 Apr 2022 22:53:03 +0200 Subject: [PATCH 60/73] Formatting --- .../expression/builtin/error/ArityError.java | 2 +- .../expression/builtin/error/CaughtPanic.java | 2 +- .../builtin/error/InvalidArrayIndexError.java | 2 +- .../builtin/error/NoSuchConversionError.java | 2 +- .../builtin/error/NoSuchMethodError.java | 2 +- .../expression/builtin/error/TypeError.java | 2 +- .../builtin/meta/ProjectDescription.java | 2 +- .../builtin/system/SystemProcessResult.java | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 2 +- .../dsl/BuiltinsMetadataProcessor.java | 36 +++++++++---------- .../enso/interpreter/dsl/MethodProcessor.java | 18 +++++----- .../enso/interpreter/dsl/TypeProcessor.java | 33 +++++++++-------- 12 files changed, 52 insertions(+), 53 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java index ed01ba120d72..648857beb36f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"expected_min","expected_max","actual"}) +@BuiltinType(params = {"expected_min", "expected_max", "actual"}) public class ArityError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 67075c279250..743932d947da 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"payload","internal_original_exception"}) +@BuiltinType(params = {"payload", "internal_original_exception"}) public class CaughtPanic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java index 89a8e39b2ecd..a3d94f379e74 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"array","index"}) +@BuiltinType(params = {"array", "index"}) public class InvalidArrayIndexError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java index 941abba73bf2..7fa5d73a7c5a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"target","that","conversion"}) +@BuiltinType(params = {"target", "that", "conversion"}) public class NoSuchConversionError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java index ab15090c8460..0fe5b29d9c9b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"target","symbol"}) +@BuiltinType(params = {"target", "symbol"}) public class NoSuchMethodError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java index 7c657eaf5999..6ec0284ad7e9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"expected","actual","name"}) +@BuiltinType(params = {"expected", "actual", "name"}) public class TypeError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java index 0549a4360ed3..07900116447f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"prim_root_file","prim_config"}) +@BuiltinType(params = {"prim_root_file", "prim_config"}) public class ProjectDescription extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java index 96d22f648e2b..88be18a52123 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"exit_code","stdout","stderr"}) +@BuiltinType(params = {"exit_code", "stdout", "stderr"}) public class SystemProcessResult extends Builtin {} diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index b3a8d801a344..67c1350116f8 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -293,7 +293,7 @@ class IrToTruffle( val function = methodDef.body match { case fn: IR.Function if isBuiltinMethod(fn.body) => - // For builtin types that own the builtin method we only check that + // For builtin types that own the builtin method we only check that // the method has been registered during the initialization of builtins // and not attempt to register it in the scope (can't redefined methods). // For non-builtin types (or modules) that own the builtin method diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java index 79e8799a3838..7949df8eb76f 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -14,19 +14,18 @@ import java.util.stream.Collectors; /** - * The base class of Builtins processors. - * Apart from any associated with a given annotation, such as generating code, - * {@code BuiltinsMetadataProcessor} detects when the processing of the last annotation in the round - * is being processed and allows for dumping any collected metadata once. + * The base class of Builtins processors. Apart from any associated with a given annotation, such as + * generating code, {@code BuiltinsMetadataProcessor} detects when the processing of the last + * annotation in the round is being processed and allows for dumping any collected metadata once. */ public abstract class BuiltinsMetadataProcessor extends AbstractProcessor { /** * Processes annotated elements, generating code for each of them, if necessary. * - * Compared to regular annotations processor, it will detect the last round of processing, - * read any existing metadata (for diff to handle separate compilation) and call - * @{code storeMetadata} to dump any metadata, if needed. + *

Compared to regular annotations processor, it will detect the last round of processing, read + * any existing metadata (for diff to handle separate compilation) and call @{code storeMetadata} + * to dump any metadata, if needed. * * @param annotations annotation being processed this round. * @param roundEnv additional round information. @@ -47,9 +46,7 @@ public final boolean process(Set annotations, RoundEnviro Map pastEntries; try { FileObject existingFile = - processingEnv - .getFiler() - .getResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); + processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", metadataPath()); try (InputStream resource = existingFile.openInputStream()) { pastEntries = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) @@ -88,7 +85,6 @@ public final boolean process(Set annotations, RoundEnviro } } - /** * A name of the resource where metadata collected during the processing should be written to. * @@ -98,19 +94,20 @@ public final boolean process(Set annotations, RoundEnviro /** * The method called at the end of the round of annotation processing. It allows to write any - * collected metadata to a related resoource (see {@link BuiltinsMetadataProcessor#metadataPath()}). + * collected metadata to a related resoource (see {@link + * BuiltinsMetadataProcessor#metadataPath()}). * * @param writer a writer to the metadata resource - * @param pastEntries entries from the previously created metadata file, if any. Entries that should - * not be appended to {@code writer} should be removed + * @param pastEntries entries from the previously created metadata file, if any. Entries that + * should not be appended to {@code writer} should be removed * @throws IOException */ protected abstract void storeMetadata(Writer writer, Map pastEntries) - throws IOException; + throws IOException; /** - * The main body of {@link #process} that needs to be implemented by the processors. - * The method is called during regular rounds if there are no outstanding errors. + * The main body of {@link #process} that needs to be implemented by the processors. The method is + * called during regular rounds if there are no outstanding errors. * * @param annotations as in {@link #process} * @param roundEnv as in {@link #process} @@ -120,9 +117,8 @@ protected abstract boolean handleProcess( Set annotations, RoundEnvironment roundEnv); /** - * Cleanup any metadata information collected during annotation processing. - * Called when all processing is done. + * Cleanup any metadata information collected during annotation processing. Called when all + * processing is done. */ protected abstract void cleanup(); - } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java index a0b89545e77d..4b4dfe41d56c 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java @@ -29,9 +29,9 @@ public class MethodProcessor extends BuiltinsMetadataProcessor { private final Map> builtinMethods = new HashMap<>(); /** - * Processes annotated elements, generating code for each of them. - * The method also records information about builtin method in an internal map that - * will be dumped on the last round of processing. + * Processes annotated elements, generating code for each of them. The method also records + * information about builtin method in an internal map that will be dumped on the last round of + * processing. * * @param annotations annotation being processed this round. * @param roundEnv additional round information. @@ -414,15 +414,15 @@ private boolean generateWarningsCheck( } /** - * Dumps the information about the collected builtin methods to {@link MethodProcessor#metadataPath()} - * resource file. + * Dumps the information about the collected builtin methods to {@link + * MethodProcessor#metadataPath()} resource file. * - * The format of a single row in the metadata file: - * : + *

The format of a single row in the metadata file: : * * @param writer a writer to the metadata resource - * @param pastEntries entries from the previously created metadata file, if any. Entries that should - * not be appended to {@code writer} should be removed + * @param pastEntries entries from the previously created metadata file, if any. Entries that + * should not be appended to {@code writer} should be removed * @throws IOException */ protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 6f6421b541aa..02dfc07b0359 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -45,37 +45,37 @@ public String[] getParamNames() { @Override protected boolean handleProcess( - Set annotations, RoundEnvironment roundEnv) { + Set annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); for (Element elt : annotatedElements) { TypeElement element = (TypeElement) elt; BuiltinType builtinTypeAnnotation = element.getAnnotation(BuiltinType.class); String pkgName = - processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); + processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); String clazzName = element.getSimpleName().toString(); // Replace CamelCase class name to Snake_Case used in Enso String ensoTypeName = clazzName.replaceAll("([^_A-Z])([A-Z])", "$1_$2"); registerBuiltinType( - processingEnv.getFiler(), - ensoTypeName, - pkgName + "." + clazzName, - builtinTypeAnnotation.params()); + processingEnv.getFiler(), + ensoTypeName, + pkgName + "." + clazzName, + builtinTypeAnnotation.params()); } } return true; } /** - * Dumps the information about the collected builtin types to {@link MethodProcessor#metadataPath()} - * resource file. + * Dumps the information about the collected builtin types to {@link + * MethodProcessor#metadataPath()} resource file. * - * The format of a single row in the metadata file: - * ::[] + *

The format of a single row in the metadata file: ::[] * * @param writer a writer to the metadata resource - * @param pastEntries entries from the previously created metadata file, if any. Entries that should - * not be appended to {@code writer} should be removed + * @param pastEntries entries from the previously created metadata file, if any. Entries that + * should not be appended to {@code writer} should be removed * @throws IOException */ @Override @@ -84,7 +84,12 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr for (Map.Entry entry : builtinTypes.get(f).entrySet()) { BuiltinTypeConstr constr = entry.getValue(); writer.append( - entry.getKey() + ":" + constr.getTpeName() + ":" + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + "\n"); + entry.getKey() + + ":" + + constr.getTpeName() + + ":" + + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + + "\n"); if (pastEntries.containsKey(entry.getKey())) { pastEntries.remove(entry.getKey()); } @@ -101,7 +106,6 @@ protected void registerBuiltinType(Filer f, String name, String clazzName, Strin classes.put(name, new BuiltinTypeConstr(clazzName, params)); } - @Override protected String metadataPath() { return META_PATH; @@ -111,5 +115,4 @@ protected String metadataPath() { protected void cleanup() { builtinTypes.clear(); } - } From 3adc0ef5bfd896ecce9143f22056d3387491da37 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 29 Apr 2022 10:25:47 +0200 Subject: [PATCH 61/73] Remove logic to handle Any/Nothing methods The initial work introduced a workaround for a "feature" that existed before builtins work. Consider a module Foo defined `src/Data/Foo.enso`: ``` type Foo type Foo a plus_one = 1 + a new x = Foo x ``` And now you define extension methods on Foo ``` from Standard.Base.Data.Foo import all Foo.two = 2 Foo.Foo.three = 3 main = x = Foo.new 0 x.two // not OK x.there // fine ``` This is how it works even in the current master. The logic in ModuleScope allowed to workaround the (hidden) name resolution ambiguity and just define `Foo.two`. This became apparent when adding methods to types such as Nothing and Any and some tests were failing. This change reverts the workaround but adds a pending test to potentially address this in the future. --- .../runtime/scope/ModuleScope.java | 12 ---------- .../test/semantic/InteropTest.scala | 4 ++-- .../test/semantic/MethodsTest.scala | 22 +++++++++++++++---- 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 09b66083d1cc..88a5194da210 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java @@ -202,18 +202,6 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { return definedHere; } - if (atom.isBuiltin()) { - // Unfortunately locally defined extensions get associated with the module rather than a type - // within a module. - // BindingsMap would need to be enhanced to resolve to the constructor rather than a module - // but - // that will likely break some use-cases as it could become ambiguous. - AtomConstructor moduleTypeInStdLib = atom.getDefinitionScope().associatedType; - definedHere = getMethodMapFor(moduleTypeInStdLib).get(lowerName); - if (definedHere != null) { - return definedHere; - } - } return imports.stream() .map(scope -> scope.getExportedMethod(atom, name)) .filter(Objects::nonNull) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index e02a6eb2aba7..7770c1e5d348 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala @@ -46,7 +46,7 @@ class InteropTest extends InterpreterTest { val code = """from Standard.Base.Data.Any import all | - |Any.method = this + |Any.Any.method = this | |main = x -> .method |""".stripMargin @@ -61,7 +61,7 @@ class InteropTest extends InterpreterTest { |from Standard.Base.Data.Text import all | |Number.add x = x + this - |Text.add x = this + x + |Text.Text.add x = this + x | |main = .add |""".stripMargin diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 20d663b1b22a..a73ccd006213 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala @@ -27,7 +27,7 @@ class MethodsTest extends InterpreterTest { """from Standard.Base.IO import all |import Standard.Base.Nothing | - |Nothing.foo = 0 + |Nothing.Nothing.foo = 0 | |main = (IO.println "foo").foo |""".stripMargin @@ -90,7 +90,7 @@ class MethodsTest extends InterpreterTest { val code = """from Standard.Base.Data.Any import all | - |Any.method = + |Any.Any.method = | x = this * this | y = x * 2 | y + 1 @@ -127,14 +127,14 @@ class MethodsTest extends InterpreterTest { "be callable for any type when defined on Any" in { val code = """from Standard.Base.Data.Any import all - |from Standard.Base.IO import all + |import Standard.Base.IO |import Standard.Base.Nothing | |type Foo |type Bar |type Baz | - |Any.method = case this of + |Any.Any.method = case this of | Foo -> 1 | Bar -> 2 | Baz -> 3 @@ -152,6 +152,20 @@ class MethodsTest extends InterpreterTest { consumeOut shouldEqual List("1", "2", "3", "0", "0", "0") } + "be callable for any type when defined on Any (resolved as a type name)" in { + import annotation.unused + @unused val code = + """from Standard.Base.Data.Any import all + | + |Any.method = 1 + | + |main = + | 2.method + |""".stripMargin + //eval(code) shouldEqual 1 + pending + } + "work as expected when defined across different constructors" in { val code = """from Standard.Base.Data.List import all From dc11b5a08b97df9df831e00c3f15be25c1445a46 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Fri, 29 Apr 2022 18:33:57 +0200 Subject: [PATCH 62/73] Auto-generate Builtins Constants BuiltinType annotation now provides an additional parameter that stores a link to the corresponding definition in stdlib. TypesFromProxy provides a single static method `fromTypeSystem` which converts from type-system type names to atoms. It is a proxy because it could easily be placed inside {@link org.enso.interpreter.runtime.builtin.Builtins}. Except that by the time Builtins is compiled it requires ConstantsGen to be present, which is being generated via the TypeProcessor at a late stage. Similarly {@link org.enso.interpreter.runtime.type.Types} requires ConstantsGen to be in the same package which creates a catch-22 situation. --- .../node/expression/builtin/Any.java | 2 +- .../node/expression/builtin/Boolean.java | 2 +- .../node/expression/builtin/Error.java | 2 +- .../node/expression/builtin/Nothing.java | 2 +- .../node/expression/builtin/error/Panic.java | 2 +- .../expression/builtin/function/Function.java | 2 +- .../expression/builtin/mutable/Array.java | 2 +- .../node/expression/builtin/mutable/Ref.java | 2 +- .../expression/builtin/number/Decimal.java | 2 +- .../expression/builtin/number/Integer.java | 2 +- .../expression/builtin/number/Number.java | 2 +- .../builtin/resource/ManagedResource.java | 2 +- .../node/expression/builtin/text/Text.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 44 +++---------- .../interpreter/runtime/type/Constants.java | 18 +---- .../enso/interpreter/runtime/type/Types.java | 53 +++++++-------- .../runtime/type/TypesFromProxy.java | 60 +++++++++++++++++ .../compiler/context/SuggestionBuilder.scala | 3 +- .../org/enso/interpreter/dsl/BuiltinType.java | 3 + .../enso/interpreter/dsl/TypeProcessor.java | 66 +++++++++++++++++-- 20 files changed, 173 insertions(+), 100 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java index 49b55f09190d..ad28f12ee774 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -2,5 +2,5 @@ import org.enso.interpreter.dsl.BuiltinType; -@BuiltinType +@BuiltinType(name = "Standard.Base.Any.Any") public class Any extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java index 3ecf88f24d37..169885fda909 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -8,5 +8,5 @@ // The name Boolean would clash with java.lang.Boolean. // Before moving this definition to the `bool` package, as we should, one would have to address that // problem first. -@BuiltinType +@BuiltinType(name = "Standard.Base.Boolean.Boolean") public class Boolean extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java index d8c41cf44e76..b9398edf89c4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java @@ -2,5 +2,5 @@ import org.enso.interpreter.dsl.BuiltinType; -@BuiltinType +@BuiltinType(name = "Standard.Base.Error.Common.Error") public class Error extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java index 16d99b042bb6..1189cf7a088f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Nothing.java @@ -2,5 +2,5 @@ import org.enso.interpreter.dsl.BuiltinType; -@BuiltinType +@BuiltinType(name = "Standard.Base.Nothing.Nothing") public class Nothing extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java index caf28b6277dc..6b4ac0462c5b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Error.Common.Panic") public class Panic extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java index 2003ce43079f..56596a32356b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Function.Function") public class Function extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java index f739483ebf34..1133dfa4caea 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Array.Array") public class Array extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java index 273f20e3a418..8336cd33ad27 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Ref.Ref") public class Ref extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java index 72e05b732bd4..18cbf5359637 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Numbers.Decimal") public class Decimal extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java index 67567d43a519..318bbd3fcda3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Numbers.Integer") public class Integer extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java index f96634396d75..0c2ee799100a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Numbers.Number") public class Number extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java index 6ecd3af1d00c..f278f438d9e6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Runtime.Resource.Managed_Resource") public class ManagedResource extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java index 3026cb57be86..c83a768f1f22 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java @@ -3,5 +3,5 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType +@BuiltinType(name = "Standard.Base.Data.Text.Text") public class Text extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 3949e02eab45..584c4362304e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -35,6 +35,7 @@ import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.Constants; +import org.enso.interpreter.runtime.type.TypesFromProxy; import org.enso.pkg.QualifiedName; /** Container class for static predefined atoms, methods, and their containing scope. */ @@ -59,7 +60,7 @@ public static class Debug { private final Error error; private final Module module; private final ModuleScope scope; - private final Number number; + public final Number number; private final Ordering ordering; private final System system; private final Special special; @@ -199,7 +200,7 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { .map( line -> { String[] builtinMeta = line.split(":"); - if (builtinMeta.length < 2 || builtinMeta.length > 3) { + if (builtinMeta.length != 4) { throw new CompilerError( "Invalid builtin metadata in: " + line + " " + builtinMeta.length); } @@ -207,11 +208,11 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { AtomConstructor builtin; builtin = new AtomConstructor(builtinMeta[0], scope, true); - if (builtinMeta.length == 2) { + if (builtinMeta[3].isEmpty()) { builtin = builtin.initializeFields(); } else { // there are some type params - String[] paramNames = builtinMeta[2].split(","); + String[] paramNames = builtinMeta[3].split(","); ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; for (int i = 0; i < paramNames.length; i++) { args[i] = @@ -406,7 +407,7 @@ public AtomConstructor falseAtom() { } /** @return the ManagedResource constructor. */ - private AtomConstructor managedResource() { + public AtomConstructor managedResource() { if (managedResource == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); managedResource = getBuiltinType(ManagedResource.class); @@ -531,40 +532,11 @@ public Module getModule() { /** * Convert from type-system type names to atoms. * - * @param typeName the fully qualified type name as defined in {@link Constants}. + * @param typeName the fully qualified type name of a builtin * @return the associated {@link org.enso.interpreter.runtime.callable.atom.Atom} if it exists, * and {@code null} otherwise */ public Atom fromTypeSystem(String typeName) { - switch (typeName) { - case Constants.ANY: - return any().newInstance(); - case Constants.ARRAY: - return array().newInstance(); - case Constants.BOOLEAN: - return bool().newInstance(); - case Constants.DECIMAL: - return number.getDecimal().newInstance(); - case Constants.ERROR: - return dataflowError().newInstance(); - case Constants.FUNCTION: - return function().newInstance(); - case Constants.INTEGER: - return number.getInteger().newInstance(); - case Constants.MANAGED_RESOURCE: - return managedResource().newInstance(); - case Constants.NOTHING: - return nothing().newInstance(); - case Constants.NUMBER: - return number.getNumber().newInstance(); - case Constants.PANIC: - return panic().newInstance(); - case Constants.REF: - return ref().newInstance(); - case Constants.TEXT: - return text().newInstance(); - default: - return null; - } + return TypesFromProxy.fromTypeSystem(this, typeName); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java index 81077d28b07f..c076067ca55e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Constants.java @@ -1,23 +1,9 @@ package org.enso.interpreter.runtime.type; -/** Hard-coded names of builtins. */ public class Constants { - public static final String ANY = "Standard.Base.Data.Any.Any"; - public static final String ARRAY = "Standard.Base.Data.Array.Array"; - public static final String BOOLEAN = "Standard.Base.Data.Boolean.Boolean"; - public static final String DECIMAL = "Standard.Base.Data.Numbers.Decimal"; - public static final String ERROR = "Standard.Base.Error.Common.Error"; - public static final String FUNCTION = "Standard.Base.Function.Function"; - public static final String INTEGER = "Standard.Base.Data.Numbers.Integer"; - public static final String MANAGED_RESOURCE = "Standard.Base.Runtime.Resource.Managed_Resource"; - public static final String NOTHING = "Standard.Base.Nothing.Nothing"; - public static final String NUMBER = "Standard.Base.Data.Numbers.Number"; - public static final String PANIC = "Standard.Base.Error.Common.Panic"; - public static final String REF = "Standard.Base.Data.Ref.Ref"; - public static final String TEXT = "Standard.Base.Data.Text.Text"; - - // Remaining constants that are not Builtins but refer to builtin-related internals + // Hard-coded names of remaining constants that are not Builtins + // but refer to builtin-related internals public static final String MODULE_SCOPE = "Standard.Builtins.Main.Module_Scope"; public static final String THUNK = "Standard.Builtins.Main.Thunk"; public static final String UNRESOLVED_SYMBOL = "Standard.Builtins.Main.Unresolved_Symbol"; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Types.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Types.java index ab8f33db8804..e6e522f2e1e7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Types.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/Types.java @@ -3,6 +3,7 @@ import com.oracle.truffle.api.dsl.TypeSystem; import com.oracle.truffle.api.interop.ArityException; import com.oracle.truffle.api.interop.UnsupportedTypeException; +// import org.enso.interpreter.runtime.ConstantsGen; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.Atom; @@ -108,35 +109,35 @@ public static void extractArguments(Object[] arguments) throws ArityException { */ public static String getName(Object value) { if (TypesGen.isLong(value) || TypesGen.isEnsoBigInteger(value)) { - return Constants.INTEGER; + return ConstantsGen.INTEGER; } else if (TypesGen.isDouble(value)) { - return Constants.DECIMAL; + return ConstantsGen.DECIMAL; } else if (TypesGen.isBoolean(value)) { - return Constants.BOOLEAN; + return ConstantsGen.BOOLEAN; } else if (TypesGen.isText(value)) { - return Constants.TEXT; + return ConstantsGen.TEXT; } else if (TypesGen.isFunction(value)) { - return Constants.FUNCTION; + return ConstantsGen.FUNCTION; } else if (TypesGen.isAtom(value)) { return TypesGen.asAtom(value).getConstructor().getQualifiedName().toString(); } else if (TypesGen.isAtomConstructor(value)) { return TypesGen.asAtomConstructor(value).getQualifiedName().toString(); } else if (TypesGen.isDataflowError(value)) { - return Constants.ERROR; + return ConstantsGen.ERROR; } else if (TypesGen.isUnresolvedSymbol(value) || TypesGen.isUnresolvedConversion(value)) { return Constants.UNRESOLVED_SYMBOL; } else if (TypesGen.isManagedResource(value)) { - return Constants.MANAGED_RESOURCE; + return ConstantsGen.MANAGED_RESOURCE; } else if (TypesGen.isArray(value)) { - return Constants.ARRAY; + return ConstantsGen.ARRAY; } else if (TypesGen.isModuleScope(value)) { return Constants.MODULE_SCOPE; } else if (TypesGen.isRef(value)) { - return Constants.REF; + return ConstantsGen.REF; } else if (TypesGen.isPanicException(value)) { - return Constants.PANIC; + return ConstantsGen.PANIC; } else if (TypesGen.isPanicSentinel(value)) { - return Constants.PANIC; + return ConstantsGen.PANIC; } else { return null; } @@ -144,7 +145,7 @@ public static String getName(Object value) { /** Check if the given type is a panic. */ public static boolean isPanic(String typeName) { - return Constants.PANIC.equals(typeName); + return ConstantsGen.PANIC.equals(typeName); } /** @@ -206,20 +207,20 @@ public static TypeGraph getTypeHierarchy() { } private static TypeGraph buildTypeHierarchy() { - TypeGraph graph = TypeGraph.fromJava(Constants.ANY); - - graph.insert(Constants.ARRAY, Constants.ANY); - graph.insert(Constants.BOOLEAN, Constants.ANY); - graph.insert(Constants.DECIMAL, Constants.NUMBER); - graph.insert(Constants.ERROR, Constants.ANY); - graph.insert(Constants.FUNCTION, Constants.ANY); - graph.insert(Constants.INTEGER, Constants.NUMBER); - graph.insert(Constants.MANAGED_RESOURCE, Constants.ANY); - graph.insert(Constants.NOTHING, Constants.ANY); - graph.insert(Constants.PANIC, Constants.ANY); - graph.insert(Constants.REF, Constants.ANY); - graph.insert(Constants.TEXT, Constants.ANY); - graph.insertWithoutParent(Constants.PANIC); + TypeGraph graph = TypeGraph.fromJava(ConstantsGen.ANY); + + graph.insert(ConstantsGen.ARRAY, ConstantsGen.ANY); + graph.insert(ConstantsGen.BOOLEAN, ConstantsGen.ANY); + graph.insert(ConstantsGen.DECIMAL, ConstantsGen.NUMBER); + graph.insert(ConstantsGen.ERROR, ConstantsGen.ANY); + graph.insert(ConstantsGen.FUNCTION, ConstantsGen.ANY); + graph.insert(ConstantsGen.INTEGER, ConstantsGen.NUMBER); + graph.insert(ConstantsGen.MANAGED_RESOURCE, ConstantsGen.ANY); + graph.insert(ConstantsGen.NOTHING, ConstantsGen.ANY); + graph.insert(ConstantsGen.PANIC, ConstantsGen.ANY); + graph.insert(ConstantsGen.REF, ConstantsGen.ANY); + graph.insert(ConstantsGen.TEXT, ConstantsGen.ANY); + graph.insertWithoutParent(ConstantsGen.PANIC); graph.insertWithoutParent(Constants.THUNK); graph.insertWithoutParent(Constants.UNRESOLVED_SYMBOL); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java new file mode 100644 index 000000000000..a33700213743 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java @@ -0,0 +1,60 @@ +package org.enso.interpreter.runtime.type; + +import org.enso.interpreter.runtime.builtin.Builtins; +import org.enso.interpreter.runtime.callable.atom.Atom; + +/** + * TypesFromProxy provides a single static method `fromTypeSystem` which converts from type-system + * type names to atoms. + * + *

It is a proxy because it could easily be placed inside {@link + * org.enso.interpreter.runtime.builtin.Builtins}. Except that by the time Builtins is compiled it + * requires ConstantsGen to be present, which is being generated via the TypeProcessor at a late + * stage. Similarly {@link org.enso.interpreter.runtime.type.Types} requires ConstantsGen to be in + * the same package which creates a catch-22 situation. + */ +public class TypesFromProxy { + + /** + * Convert from type-system type names to atoms. + * + * @param builtins a reference to {@link org.enso.interpreter.runtime.builtin.Builtins} where all + * builtins can be referenced from + * @param typeName the fully qualified type name as defined in {@link Constants} or {@link + * ConstantsGen} + * @return the associated {@link org.enso.interpreter.runtime.callable.atom.Atom} if it exists, + * and {@code null} otherwise + */ + public static Atom fromTypeSystem(Builtins builtins, String typeName) { + switch (typeName) { + case ConstantsGen.ANY: + return builtins.any().newInstance(); + case ConstantsGen.ARRAY: + return builtins.array().newInstance(); + case ConstantsGen.BOOLEAN: + return builtins.bool().newInstance(); + case ConstantsGen.DECIMAL: + return builtins.number.getDecimal().newInstance(); + case ConstantsGen.ERROR: + return builtins.dataflowError().newInstance(); + case ConstantsGen.FUNCTION: + return builtins.function().newInstance(); + case ConstantsGen.INTEGER: + return builtins.number.getInteger().newInstance(); + case ConstantsGen.MANAGED_RESOURCE: + return builtins.managedResource().newInstance(); + case ConstantsGen.NOTHING: + return builtins.nothing().newInstance(); + case ConstantsGen.NUMBER: + return builtins.number.getNumber().newInstance(); + case ConstantsGen.PANIC: + return builtins.panic().newInstance(); + case ConstantsGen.REF: + return builtins.ref().newInstance(); + case ConstantsGen.TEXT: + return builtins.text().newInstance(); + default: + return null; + } + } +} diff --git a/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala index ac2ca8a2b009..4fdf4f68682a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala @@ -8,7 +8,6 @@ import org.enso.compiler.pass.resolve.{ MethodDefinitions, TypeSignatures } -import org.enso.interpreter.runtime.`type`.Constants import org.enso.pkg.QualifiedName import org.enso.polyglot.Suggestion import org.enso.polyglot.data.Tree @@ -672,6 +671,6 @@ object SuggestionBuilder { } - val Any: String = Constants.ANY + val Any: String = "Standard.Base.Any.Any" } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java index d0306337067c..3b8225421e29 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -10,6 +10,9 @@ @Retention(RetentionPolicy.SOURCE) public @interface BuiltinType { + /** Fully qualified name as available in stdlib */ + String name() default ""; + /** * Comma-separated list of parameters of builting type * diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 02dfc07b0359..f37f7becb8e2 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -6,12 +6,11 @@ import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; +import javax.tools.JavaFileObject; import java.io.IOException; +import java.io.PrintWriter; import java.io.Writer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.StringUtils; @@ -23,13 +22,19 @@ public class TypeProcessor extends BuiltinsMetadataProcessor { private class BuiltinTypeConstr { private String tpeName; + private String fullName; private String[] paramNames; - BuiltinTypeConstr(String tpeName, String[] params) { + BuiltinTypeConstr(String tpeName, String fullName, String[] params) { this.tpeName = tpeName; + this.fullName = fullName; this.paramNames = params; } + public String getFullName() { + return fullName; + } + public String getTpeName() { return tpeName; } @@ -60,6 +65,7 @@ protected boolean handleProcess( processingEnv.getFiler(), ensoTypeName, pkgName + "." + clazzName, + builtinTypeAnnotation.name(), builtinTypeAnnotation.params()); } } @@ -80,7 +86,9 @@ protected boolean handleProcess( */ @Override protected void storeMetadata(Writer writer, Map pastEntries) throws IOException { + JavaFileObject gen = processingEnv.getFiler().createSourceFile(ConstantsGenFullClassname); for (Filer f : builtinTypes.keySet()) { + System.out.println("foo" + f.toString()); for (Map.Entry entry : builtinTypes.get(f).entrySet()) { BuiltinTypeConstr constr = entry.getValue(); writer.append( @@ -88,6 +96,8 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr + ":" + constr.getTpeName() + ":" + + constr.getFullName() + + ":" + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + "\n"); if (pastEntries.containsKey(entry.getKey())) { @@ -95,15 +105,53 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr } } } + try (PrintWriter out = new PrintWriter(gen.openWriter())) { + out.println("package " + ConstantsGenPkg + ";"); + out.println(); + out.println("public class " + ConstantsGenClass + " {"); + out.println(); + for (Filer f : builtinTypes.keySet()) { + for (Map.Entry entry : builtinTypes.get(f).entrySet()) { + BuiltinTypeConstr constr = entry.getValue(); + if (!constr.getFullName().isEmpty()) { + out.println( + " public static final String " + + entry.getKey().toUpperCase() + + " = \"" + + constr.getFullName() + + "\";"); + } + } + } + + pastEntries + .values() + .forEach( + entry -> { + String[] elements = entry.split(":"); + if (!elements[2].isEmpty()) { + out.println( + " public static void final String " + + elements[0].toUpperCase() + + " = \"" + + elements[2] + + "\";"); + } + }); + + out.println(); + out.println("}"); + } } - protected void registerBuiltinType(Filer f, String name, String clazzName, String[] params) { + protected void registerBuiltinType( + Filer f, String name, String clazzName, String fullName, String[] params) { Map classes = builtinTypes.get(f); if (classes == null) { classes = new HashMap<>(); builtinTypes.put(f, classes); } - classes.put(name, new BuiltinTypeConstr(clazzName, params)); + classes.put(name, new BuiltinTypeConstr(clazzName, fullName, params)); } @Override @@ -115,4 +163,8 @@ protected String metadataPath() { protected void cleanup() { builtinTypes.clear(); } + + private static final String ConstantsGenPkg = "org.enso.interpreter.runtime.type"; + private static final String ConstantsGenClass = "ConstantsGen"; + private static final String ConstantsGenFullClassname = ConstantsGenPkg + "." + ConstantsGenClass; } From 9414fcea6c0c6934ab705672811d6981805c189c Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 10:40:16 +0200 Subject: [PATCH 63/73] Test adjustments to the previous commit --- .../interpreter/runtime/builtin/Builtins.java | 8 +- .../test/instrument/RuntimeErrorsTest.scala | 52 +++--- .../instrument/RuntimeInstrumentTest.scala | 70 ++++---- .../test/instrument/RuntimeServerTest.scala | 154 +++++++++--------- .../RuntimeSuggestionUpdatesTest.scala | 72 ++++---- .../RuntimeVisualisationsTest.scala | 26 +-- .../test/instrument/TestMessages.scala | 6 +- .../enso/interpreter/dsl/TypeProcessor.java | 8 +- 8 files changed, 198 insertions(+), 198 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 584c4362304e..ac14edd1ea33 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -200,19 +200,19 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { .map( line -> { String[] builtinMeta = line.split(":"); - if (builtinMeta.length != 4) { + if (builtinMeta.length < 2 || builtinMeta.length > 4) { throw new CompilerError( - "Invalid builtin metadata in: " + line + " " + builtinMeta.length); + "Invalid builtin metadata in: " + line); } AtomConstructor builtin; builtin = new AtomConstructor(builtinMeta[0], scope, true); - if (builtinMeta[3].isEmpty()) { + if (builtinMeta.length < 3 || builtinMeta[2].isEmpty()) { builtin = builtin.initializeFields(); } else { // there are some type params - String[] paramNames = builtinMeta[3].split(","); + String[] paramNames = builtinMeta[2].split(","); ArgumentDefinition[] args = new ArgumentDefinition[paramNames.length]; for (int i = 0; i < paramNames.length; i++) { args[i] = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 87813ad85d45..386ec96bc1af 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -3,7 +3,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager import org.enso.interpreter.instrument.execution.Timer -import org.enso.interpreter.runtime.`type`.Constants +import org.enso.interpreter.runtime.`type`.ConstantsGen import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} import org.enso.polyglot._ @@ -417,8 +417,8 @@ class RuntimeErrorsTest Seq(xId) ) ), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual Seq("42") @@ -491,8 +491,8 @@ class RuntimeErrorsTest xId, Api.ExpressionUpdate.Payload.DataflowError(Seq(xId)) ), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual Seq("42") @@ -558,7 +558,7 @@ class RuntimeErrorsTest yId, Api.ExpressionUpdate.Payload.DataflowError(Seq(xId)) ), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual Seq("(Error: MyError)") @@ -578,8 +578,8 @@ class RuntimeErrorsTest ) ) context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("1234567890123456788") @@ -630,8 +630,8 @@ class RuntimeErrorsTest ) ) context.receiveN(3) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("499999999999") @@ -698,7 +698,7 @@ class RuntimeErrorsTest yId, Api.ExpressionUpdate.Payload.DataflowError(Seq(xId)) ), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual Seq("(Error: MyError1)") @@ -789,7 +789,7 @@ class RuntimeErrorsTest yId, Api.ExpressionUpdate.Payload.DataflowError(Seq(fooThrowId, xId)) ), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual Seq("(Error: MyError1)") @@ -908,9 +908,9 @@ class RuntimeErrorsTest ) context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("1234567890123456788") @@ -1020,9 +1020,9 @@ class RuntimeErrorsTest ) ) context.receiveN(4) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("101") @@ -1250,11 +1250,11 @@ class RuntimeErrorsTest TestMessages.update( contextId, xId, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, moduleName, "foo") ), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResId, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("3") @@ -1326,7 +1326,7 @@ class RuntimeErrorsTest TestMessages.update( contextId, mainResId, - Constants.NOTHING + ConstantsGen.NOTHING ), context.executionComplete(contextId) ) @@ -1350,10 +1350,10 @@ class RuntimeErrorsTest TestMessages.update( contextId, xId, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, moduleName, "foo") ), - TestMessages.update(contextId, yId, Constants.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("3") @@ -1455,8 +1455,8 @@ class RuntimeErrorsTest ) ) context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( - TestMessages.update(contextId, x1Id, Constants.NOTHING), - TestMessages.update(contextId, mainRes1Id, Constants.NOTHING), + TestMessages.update(contextId, x1Id, ConstantsGen.NOTHING), + TestMessages.update(contextId, mainRes1Id, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("MyError") diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 0f7afb9a054a..dd3b1d92e2ca 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -3,7 +3,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager import org.enso.interpreter.instrument.execution.Timer -import org.enso.interpreter.runtime.`type`.Constants +import org.enso.interpreter.runtime.`type`.{ConstantsGen, Constants} import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} import org.enso.polyglot._ @@ -145,7 +145,7 @@ class RuntimeInstrumentTest ) context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, mainBody, Constants.INTEGER), + TestMessages.update(contextId, mainBody, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -192,7 +192,7 @@ class RuntimeInstrumentTest ) context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, mainBody, Constants.TEXT), + TestMessages.update(contextId, mainBody, ConstantsGen.TEXT), context.executionComplete(contextId) ) } @@ -307,11 +307,11 @@ class RuntimeInstrumentTest ) context.receiveNIgnoreStdLib(7) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, xExpr, Constants.INTEGER), - TestMessages.update(contextId, yExpr, Constants.INTEGER), - TestMessages.update(contextId, zExpr, Constants.INTEGER), - TestMessages.update(contextId, mainResExpr, Constants.NOTHING), - TestMessages.update(contextId, mainBody, Constants.NOTHING), + TestMessages.update(contextId, xExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, yExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, zExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResExpr, ConstantsGen.NOTHING), + TestMessages.update(contextId, mainBody, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -367,11 +367,11 @@ class RuntimeInstrumentTest ) context.receiveNIgnoreStdLib(7) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, xExpr, Constants.INTEGER), - TestMessages.update(contextId, yExpr, Constants.INTEGER), - TestMessages.update(contextId, mainRes1Expr, Constants.INTEGER), - TestMessages.update(contextId, mainResExpr, Constants.NOTHING), - TestMessages.update(contextId, mainBody, Constants.NOTHING), + TestMessages.update(contextId, xExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, yExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainRes1Expr, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResExpr, ConstantsGen.NOTHING), + TestMessages.update(contextId, mainBody, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -424,9 +424,9 @@ class RuntimeInstrumentTest ) context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, fExpr, Constants.FUNCTION), - TestMessages.update(contextId, mainResExpr, Constants.INTEGER), - TestMessages.update(contextId, mainBody, Constants.INTEGER), + TestMessages.update(contextId, fExpr, ConstantsGen.FUNCTION), + TestMessages.update(contextId, mainResExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainBody, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -479,9 +479,9 @@ class RuntimeInstrumentTest ) context.receiveN(6) should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, fExpr, Constants.FUNCTION), - TestMessages.update(contextId, xExpr, Constants.INTEGER), - TestMessages.update(contextId, mainResExpr, Constants.INTEGER), + TestMessages.update(contextId, fExpr, ConstantsGen.FUNCTION), + TestMessages.update(contextId, xExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainResExpr, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -541,11 +541,11 @@ class RuntimeInstrumentTest .update( contextId, xExpr, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.Main", "Enso_Test.Test.Main", "f") ), - TestMessages.update(contextId, mainRes, Constants.INTEGER), - TestMessages.update(contextId, mainExpr, Constants.INTEGER), + TestMessages.update(contextId, mainRes, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainExpr, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -602,10 +602,10 @@ class RuntimeInstrumentTest ) context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, aExpr, Constants.INTEGER), - TestMessages.update(contextId, fApp, Constants.INTEGER), - TestMessages.update(contextId, mainRes, Constants.NOTHING), - TestMessages.update(contextId, mainExpr, Constants.NOTHING), + TestMessages.update(contextId, aExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, fApp, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), + TestMessages.update(contextId, mainExpr, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -662,9 +662,9 @@ class RuntimeInstrumentTest ) context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, aExpr, Constants.INTEGER), - TestMessages.update(contextId, lamArg, Constants.INTEGER), - TestMessages.update(contextId, mainRes, Constants.NOTHING), + TestMessages.update(contextId, aExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, lamArg, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -719,9 +719,9 @@ class RuntimeInstrumentTest ) context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, aExpr, Constants.INTEGER), - TestMessages.update(contextId, lamArg, Constants.INTEGER), - TestMessages.update(contextId, mainRes, Constants.NOTHING), + TestMessages.update(contextId, aExpr, ConstantsGen.INTEGER), + TestMessages.update(contextId, lamArg, ConstantsGen.INTEGER), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("2") @@ -968,9 +968,9 @@ class RuntimeInstrumentTest ) context.receiveN(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, arg1, Constants.INTEGER), - TestMessages.update(contextId, arg2, Constants.INTEGER), - TestMessages.update(contextId, arg3, Constants.INTEGER), + TestMessages.update(contextId, arg1, ConstantsGen.INTEGER), + TestMessages.update(contextId, arg2, ConstantsGen.INTEGER), + TestMessages.update(contextId, arg3, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index aa50c980d61f..b316f3bcb80e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -3,7 +3,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager import org.enso.interpreter.instrument.execution.Timer -import org.enso.interpreter.runtime.`type`.{Constants, Types} +import org.enso.interpreter.runtime.`type`.{ConstantsGen, Types} import org.enso.interpreter.runtime.{Context => EnsoContext} import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} @@ -143,7 +143,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idMainX, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -160,11 +160,11 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idMainY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", - Constants.NUMBER, + ConstantsGen.NUMBER, "foo" ) ), @@ -183,7 +183,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -200,7 +200,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idFooY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -217,7 +217,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idFooZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -264,7 +264,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( idMainY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", @@ -287,7 +287,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", @@ -469,10 +469,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "foo") ), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("1") @@ -572,7 +572,7 @@ class RuntimeServerTest TestMessages.update( contextId, idMainX, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer( "Enso_Test.Test.Main", "Enso_Test.Test.Main.Quux", @@ -582,24 +582,24 @@ class RuntimeServerTest TestMessages.update( contextId, idMainY, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.Main", "Enso_Test.Test.Main", "bar") ), TestMessages.update(contextId, idMainM, "Enso_Test.Test.A.A"), TestMessages.update( contextId, idMainP, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.A", "Enso_Test.Test.A.A", "foo") ), TestMessages.update( contextId, idMainQ, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.A", "Enso_Test.Test.A", "bar") ), - TestMessages.update(contextId, idMainF, Constants.INTEGER), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMainF, ConstantsGen.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("79") @@ -654,10 +654,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "foo") ), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -713,10 +713,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "foo") ), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("3") @@ -774,10 +774,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainBar, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "bar") ), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("42") @@ -837,10 +837,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainBar, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "bar") ), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("10") @@ -896,10 +896,10 @@ class RuntimeServerTest TestMessages.update( contextId, idMainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "foo") ), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -965,10 +965,10 @@ class RuntimeServerTest .update( contextId, mainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.Main", "Enso_Test.Test.Main", "foo") ), - TestMessages.update(contextId, mainRes, Constants.NOTHING), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("4") @@ -982,8 +982,8 @@ class RuntimeServerTest ) context.receiveN(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, fooX, Constants.INTEGER), - TestMessages.update(contextId, fooRes, Constants.INTEGER), + TestMessages.update(contextId, fooX, ConstantsGen.INTEGER), + TestMessages.update(contextId, fooRes, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("4") @@ -1015,7 +1015,7 @@ class RuntimeServerTest .update( contextId, mainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.Main", "Enso_Test.Test.Main", "foo") ), context.executionComplete(contextId) @@ -1062,7 +1062,7 @@ class RuntimeServerTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1140,9 +1140,9 @@ class RuntimeServerTest ) context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, idResult, Constants.INTEGER), - TestMessages.update(contextId, idPrintln, Constants.NOTHING), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idResult, ConstantsGen.INTEGER), + TestMessages.update(contextId, idPrintln, ConstantsGen.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("1337") @@ -1162,7 +1162,7 @@ class RuntimeServerTest ) ) context.receiveN(2) should contain theSameElementsAs Seq( - TestMessages.update(contextId, idResult, Constants.TEXT), + TestMessages.update(contextId, idResult, ConstantsGen.TEXT), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("Hi") @@ -1229,9 +1229,9 @@ class RuntimeServerTest ) context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, idMainA, Constants.INTEGER), - TestMessages.update(contextId, idMainP, Constants.NOTHING), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMainA, ConstantsGen.INTEGER), + TestMessages.update(contextId, idMainP, ConstantsGen.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("144") @@ -1254,8 +1254,8 @@ class RuntimeServerTest TestMessages.update( contextId, idMainA, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "x") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "x") ), context.executionComplete(contextId) ) @@ -1296,7 +1296,7 @@ class RuntimeServerTest TestMessages.update( contextId, idMainA, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "pie") ), context.executionComplete(contextId) @@ -1321,7 +1321,7 @@ class RuntimeServerTest TestMessages.update( contextId, idMainA, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "uwu") ), context.executionComplete(contextId) @@ -1346,7 +1346,7 @@ class RuntimeServerTest TestMessages.update( contextId, idMainA, - Constants.TEXT, + ConstantsGen.TEXT, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "hie") ), context.executionComplete(contextId) @@ -1368,7 +1368,7 @@ class RuntimeServerTest ) ) context.receiveN(2) should contain theSameElementsAs Seq( - TestMessages.update(contextId, idMainA, Constants.TEXT), + TestMessages.update(contextId, idMainA, ConstantsGen.TEXT), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("Hello!") @@ -1433,24 +1433,24 @@ class RuntimeServerTest ) context.receiveNIgnoreStdLib(6) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, idMain, Constants.NOTHING), + TestMessages.update(contextId, idMain, ConstantsGen.NOTHING), TestMessages.update( contextId, id1, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded") ), TestMessages.update( contextId, id2, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.TEXT, "overloaded") ), TestMessages.update( contextId, id3, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded") ), context.executionComplete(contextId) ) @@ -1477,21 +1477,21 @@ class RuntimeServerTest TestMessages.update( contextId, id1, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded"), + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded"), fromCache = true ), TestMessages.update( contextId, id2, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.TEXT, "overloaded") ), TestMessages.update( contextId, id3, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded") ), context.executionComplete(contextId) ) @@ -1518,21 +1518,21 @@ class RuntimeServerTest TestMessages.update( contextId, id1, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded"), + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded"), fromCache = true ), TestMessages.update( contextId, id2, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.TEXT, "overloaded") ), TestMessages.update( contextId, id3, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded") ), context.executionComplete(contextId) ) @@ -1559,21 +1559,21 @@ class RuntimeServerTest TestMessages.update( contextId, id1, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded"), + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded"), fromCache = true ), TestMessages.update( contextId, id2, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.TEXT, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.TEXT, "overloaded") ), TestMessages.update( contextId, id3, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "overloaded") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "overloaded") ), context.executionComplete(contextId) ) @@ -1626,8 +1626,8 @@ class RuntimeServerTest ) context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, xId, Constants.FUNCTION), - TestMessages.update(contextId, mainRes, Constants.NOTHING), + TestMessages.update(contextId, xId, ConstantsGen.FUNCTION), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -1738,7 +1738,7 @@ class RuntimeServerTest ) context.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1795,7 +1795,7 @@ class RuntimeServerTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -3157,8 +3157,8 @@ class RuntimeServerTest TestMessages.update( contextId, context.Main.idMainY, - Constants.INTEGER, - Api.MethodPointer("Enso_Test.Foo.Main", Constants.NUMBER, "foo") + ConstantsGen.INTEGER, + Api.MethodPointer("Enso_Test.Foo.Main", ConstantsGen.NUMBER, "foo") ), context.executionComplete(contextId) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index f4a62269a23f..0ad113234ee6 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -2,7 +2,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager -import org.enso.interpreter.runtime.`type`.Constants +import org.enso.interpreter.runtime.`type`.ConstantsGen import org.enso.pkg.{Package, PackageManager} import org.enso.polyglot._ import org.enso.polyglot.data.Tree @@ -169,7 +169,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -233,7 +233,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -247,7 +247,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(4, 16) @@ -319,7 +319,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -333,7 +333,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(4, 16) @@ -356,7 +356,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "y", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(5, 18) @@ -425,7 +425,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -439,7 +439,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(5, 18) @@ -462,14 +462,14 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "y", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(5, 18) ) ), Api.SuggestionAction.Modify( - returnType = Some(Constants.NUMBER), + returnType = Some(ConstantsGen.NUMBER), scope = Some( Suggestion.Scope( Suggestion.Position(2, 6), @@ -541,7 +541,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -555,7 +555,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(6, 18) @@ -578,7 +578,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "y", - Constants.NUMBER, + ConstantsGen.NUMBER, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(6, 18) @@ -613,10 +613,10 @@ class RuntimeSuggestionUpdatesTest None ), Suggestion - .Argument("x", Constants.ANY, false, false, None) + .Argument("x", ConstantsGen.ANY, false, false, None) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -683,10 +683,10 @@ class RuntimeSuggestionUpdatesTest None ), Suggestion - .Argument("x", Constants.ANY, false, false, None) + .Argument("x", ConstantsGen.ANY, false, false, None) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -700,7 +700,7 @@ class RuntimeSuggestionUpdatesTest Api.SuggestionArgumentAction.Add( 2, Suggestion - .Argument("b", Constants.ANY, false, false, None) + .Argument("b", ConstantsGen.ANY, false, false, None) ) ) ), @@ -810,7 +810,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -824,7 +824,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(4, 6), Suggestion.Position(9, 0) @@ -845,16 +845,16 @@ class RuntimeSuggestionUpdatesTest Seq( Suggestion.Argument( "this", - Constants.TEXT, + ConstantsGen.TEXT, false, false, None ), Suggestion - .Argument("arg", Constants.ANY, false, false, None) + .Argument("arg", ConstantsGen.ANY, false, false, None) ), - Constants.TEXT, - Constants.ANY, + ConstantsGen.TEXT, + ConstantsGen.ANY, None, None, None @@ -872,16 +872,16 @@ class RuntimeSuggestionUpdatesTest Seq( Suggestion.Argument( "this", - Constants.NUMBER, + ConstantsGen.NUMBER, false, false, None ), Suggestion - .Argument("arg", Constants.ANY, false, false, None) + .Argument("arg", ConstantsGen.ANY, false, false, None) ), - Constants.NUMBER, - Constants.ANY, + ConstantsGen.NUMBER, + ConstantsGen.ANY, None, None, None @@ -983,7 +983,7 @@ class RuntimeSuggestionUpdatesTest "MkA", List( Suggestion - .Argument("a", Constants.ANY, false, false, None) + .Argument("a", ConstantsGen.ANY, false, false, None) ), "Enso_Test.Test.A.MkA", None, @@ -1011,7 +1011,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.A.MkA", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -1029,14 +1029,14 @@ class RuntimeSuggestionUpdatesTest List( Suggestion.Argument( "this", - Constants.INTEGER, + ConstantsGen.INTEGER, false, false, None ) ), - Constants.INTEGER, - Constants.ANY, + ConstantsGen.INTEGER, + ConstantsGen.ANY, None, None, None @@ -1061,7 +1061,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.A", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -1122,7 +1122,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index adfab4bde244..147b17c703ba 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -3,7 +3,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager import org.enso.interpreter.instrument.execution.Timer -import org.enso.interpreter.runtime.`type`.Constants +import org.enso.interpreter.runtime.`type`.ConstantsGen import org.enso.interpreter.runtime.{Context => EnsoContext} import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} @@ -142,7 +142,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idMainX, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -159,11 +159,11 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idMainY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", - Constants.NUMBER, + ConstantsGen.NUMBER, "foo" ) ), @@ -182,7 +182,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -199,7 +199,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idFooY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -216,7 +216,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idFooZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -294,7 +294,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMainRes, Constants.INTEGER), + TestMessages.update(contextId, idMainRes, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1262,7 +1262,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1322,7 +1322,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1410,7 +1410,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1484,7 +1484,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1589,7 +1589,7 @@ class RuntimeVisualisationsTest context.Main.Update.mainX(contextId), context.Main.Update.mainY(contextId), context.Main.Update.mainZ(contextId), - TestMessages.update(contextId, idMain, Constants.INTEGER), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/TestMessages.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/TestMessages.scala index 8c81c3747933..1b7a4a4a13d2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/TestMessages.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/TestMessages.scala @@ -2,7 +2,7 @@ package org.enso.interpreter.test.instrument import java.util.UUID -import org.enso.interpreter.runtime.`type`.Constants +import org.enso.interpreter.runtime.`type`.ConstantsGen import org.enso.polyglot.runtime.Runtime.Api /** Helper methods for creating test messages. */ @@ -201,7 +201,7 @@ object TestMessages { Set( Api.ExpressionUpdate( expressionId, - Some(Constants.ERROR), + Some(ConstantsGen.ERROR), methodPointerOpt, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -261,7 +261,7 @@ object TestMessages { Set( Api.ExpressionUpdate( expressionId, - Some(Constants.PANIC), + Some(ConstantsGen.PANIC), methodPointer, Vector(Api.ProfilingInfo.ExecutionTime(0)), false, diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index f37f7becb8e2..f9b07227b39b 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -96,9 +96,9 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr + ":" + constr.getTpeName() + ":" - + constr.getFullName() - + ":" + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + + ":" + + constr.getFullName() + "\n"); if (pastEntries.containsKey(entry.getKey())) { pastEntries.remove(entry.getKey()); @@ -129,12 +129,12 @@ protected void storeMetadata(Writer writer, Map pastEntries) thr .forEach( entry -> { String[] elements = entry.split(":"); - if (!elements[2].isEmpty()) { + if (!elements[3].isEmpty()) { out.println( " public static void final String " + elements[0].toUpperCase() + " = \"" - + elements[2] + + elements[3] + "\";"); } }); From fa4ca5b41fafcb1b523de4a391dce1789225f5c0 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 10:47:23 +0200 Subject: [PATCH 64/73] Update distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Radosław Waśko --- .../lib/Standard/Base/0.0.0-dev/src/Error/Common.enso | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 490403e7023f..b15632960019 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -420,10 +420,11 @@ type Inexhaustive_Pattern_Match_Error scrutinee does not match the expected number of arguments. Arguments: - - expected: the expected number of arguments. + - expected_min: the minimum expected number of arguments. + - expected_max: the maximum expected number of arguments. - actual: the actual number of arguments passed. @Builtin_Type -type Arity_Error expected actual +type Arity_Error expected_min expected_max actual ## The error thrown when the program attempts to read from a state slot that has not yet been initialized. From cba36f3a5b31942414145d95cdb419b84f303ea2 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 10:49:19 +0200 Subject: [PATCH 65/73] Make formatter happy again --- .../java/org/enso/interpreter/runtime/builtin/Builtins.java | 3 +-- .../interpreter/test/instrument/RuntimeInstrumentTest.scala | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index ac14edd1ea33..531f3c296f8c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -201,8 +201,7 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { line -> { String[] builtinMeta = line.split(":"); if (builtinMeta.length < 2 || builtinMeta.length > 4) { - throw new CompilerError( - "Invalid builtin metadata in: " + line); + throw new CompilerError("Invalid builtin metadata in: " + line); } AtomConstructor builtin; diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index dd3b1d92e2ca..db98b1043ffc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -3,7 +3,7 @@ package org.enso.interpreter.test.instrument import org.enso.distribution.FileSystem import org.enso.distribution.locking.ThreadSafeFileLockManager import org.enso.interpreter.instrument.execution.Timer -import org.enso.interpreter.runtime.`type`.{ConstantsGen, Constants} +import org.enso.interpreter.runtime.`type`.{Constants, ConstantsGen} import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} import org.enso.polyglot._ From 7bf6261c77266b2ea60b353145713bf2e4e85363 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 13:02:18 +0200 Subject: [PATCH 66/73] DRY Avoiding the `CompilationFinal` logic all over the place by abstracting it to a separate class. Minor cleanups as well. --- .../Standard/Base/0.0.0-dev/src/System.enso | 4 +- .../BooleanConstructorBranchNode.java | 1 - .../builtin/bool/CompareToNode.java | 2 +- .../expression/builtin/bool/EqualsNode.java | 2 +- .../expression/builtin/debug}/Debug.java | 2 +- .../expression/constant/ConstructorNode.java | 4 +- .../interpreter/runtime/builtin/Bool.java | 41 ++--- .../builtin/BuiltinAtomConstructor.java | 32 ++++ .../interpreter/runtime/builtin/Builtins.java | 152 +++++----------- .../runtime/builtin/DataflowError.java | 28 --- .../interpreter/runtime/builtin/Error.java | 162 +++++------------- .../interpreter/runtime/builtin/Number.java | 62 ++----- .../interpreter/runtime/builtin/Ordering.java | 46 ++--- .../interpreter/runtime/builtin/System.java | 17 +- .../callable/atom/AtomConstructor.java | 2 +- .../dispatch/DefaultBooleanExports.java | 21 +-- .../runtime/type/TypesFromProxy.java | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 10 +- 18 files changed, 192 insertions(+), 398 deletions(-) rename engine/runtime/src/main/java/org/enso/interpreter/{runtime/builtin => node/expression/builtin/debug}/Debug.java (72%) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/DataflowError.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso index b71580ca7676..633a4e2e5a33 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso @@ -1,7 +1,5 @@ ## Functionality for interacting with the host system. -type System - ## PRIVATE Create a system process, returning the exit code, and the outputs to both @@ -57,4 +55,4 @@ os = @Builtin_Method "System.os" - stdout: Any values printed to standard out by the child process. - stderr: Any values printed to standard error by the child process. @Builtin_Type -type System_Process_Result exit_code stdout stderr \ No newline at end of file +type System_Process_Result exit_code stdout stderr diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java index b627577c543d..40cc6d436cf0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java @@ -8,7 +8,6 @@ import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.NodeInfo; import com.oracle.truffle.api.profiles.ConditionProfile; -import org.enso.interpreter.runtime.builtin.Bool; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index c0a2d610df90..ed054a3fd623 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -32,7 +32,7 @@ Atom doBoolean(Boolean _this, Boolean that) { @Specialization Atom doOther(Boolean _this, Object that) { CompilerDirectives.transferToInterpreter(); - var bool = Context.get(this).getBuiltins().bool().newInstance(); + var bool = Context.get(this).getBuiltins().bool().getBool().newInstance(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java index 0b551cabd1b0..b0f6c55f4573 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java @@ -36,6 +36,6 @@ boolean doOther(Object _this, Object that) { } AtomConstructor getBooleanConstructor() { - return Context.get(this).getBuiltins().bool(); + return Context.get(this).getBuiltins().bool().getBool(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java similarity index 72% rename from engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java rename to engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java index 9cbcd47be810..2c5909e209f0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Debug.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java @@ -1,4 +1,4 @@ -package org.enso.interpreter.runtime.builtin; +package org.enso.interpreter.node.expression.builtin.debug; import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java index 3a0bb3f0291e..f37c816e5c0f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java @@ -35,10 +35,10 @@ public static ConstructorNode build(AtomConstructor constructor) { @Specialization Object doExecute(VirtualFrame frame) { var builtins = Context.get(this).getBuiltins(); - if (constructor == builtins.trueAtom()) { + if (constructor == builtins.bool().getTrue()) { return true; } - if (constructor == builtins.falseAtom()) { + if (constructor == builtins.bool().getFalse()) { return false; } if (constructor.getArity() == 0) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java index dd5cdf2be930..bea8de6b5fd4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java @@ -1,51 +1,34 @@ package org.enso.interpreter.runtime.builtin; -import org.enso.interpreter.Language; +import org.enso.interpreter.node.expression.builtin.Boolean; import org.enso.interpreter.node.expression.builtin.bool.*; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; /** A container class for all Boolean-related stdlib builtins. */ public class Bool { - private final AtomConstructor tru; - private final AtomConstructor fls; - private final AtomConstructor bool; + private final BuiltinAtomConstructor tru; + private final BuiltinAtomConstructor fls; + private final BuiltinAtomConstructor bool; - /** - * Creates and registers all the boolean constructors. - * - * @param language the current language instance. - * @param scope the scope to register constructors and methods in. - */ - public Bool(Language language, ModuleScope scope) { - bool = new AtomConstructor("Boolean", scope).initializeFields(); - scope.registerConstructor(bool); - scope.registerMethod(bool, "if_then_else", IfThenElseMethodGen.makeFunction(language)); - scope.registerMethod(bool, "if_then", IfThenMethodGen.makeFunction(language)); - scope.registerMethod(bool, "to_text", ToTextMethodGen.makeFunction(language)); - scope.registerMethod(bool, "compare_to", CompareToMethodGen.makeFunction(language)); - scope.registerMethod(bool, "&&", AndMethodGen.makeFunction(language)); - scope.registerMethod(bool, "||", OrMethodGen.makeFunction(language)); - scope.registerMethod(bool, "==", EqualsMethodGen.makeFunction(language)); - scope.registerMethod(bool, "not", NotMethodGen.makeFunction(language)); - tru = new AtomConstructor("True", scope).initializeFields(); - scope.registerConstructor(tru); - fls = new AtomConstructor("False", scope).initializeFields(); - scope.registerConstructor(fls); + /** Creates builders for all the boolean constructors. */ + public Bool(Builtins builtins) { + bool = new BuiltinAtomConstructor(builtins, Boolean.class); + tru = new BuiltinAtomConstructor(builtins, True.class); + fls = new BuiltinAtomConstructor(builtins, False.class); } /** @return the atom constructor for {@code True}. */ public AtomConstructor getTrue() { - return tru; + return tru.constructor(); } /** @return the atom constructor for {@code False}. */ public AtomConstructor getFalse() { - return fls; + return fls.constructor(); } /** @return the atom constructor for {@code Boolean}. */ public AtomConstructor getBool() { - return bool; + return bool.constructor(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java new file mode 100644 index 000000000000..8f87dc329b14 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java @@ -0,0 +1,32 @@ +package org.enso.interpreter.runtime.builtin; + +import com.oracle.truffle.api.CompilerDirectives; +import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; + +import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; + +public class BuiltinAtomConstructor { + private final Builtins builtins; + private final Class type; + + @CompilerDirectives.CompilationFinal AtomConstructor atom; + + public BuiltinAtomConstructor(Builtins builtins, Class type) { + this.builtins = builtins; + this.type = type; + } + + public AtomConstructor constructor() { + if (atom == null) { + transferToInterpreterAndInvalidate(); + atom = builtins.getBuiltinType(type); + } + return atom; + } + + Atom newInstance(Object... args) { + return constructor().newInstance(args); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 531f3c296f8c..a4f24abf406a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -19,9 +19,7 @@ import org.enso.interpreter.dsl.TypeProcessor; import org.enso.interpreter.dsl.model.MethodDefinition; import org.enso.interpreter.node.expression.builtin.*; -import org.enso.interpreter.node.expression.builtin.Boolean; -import org.enso.interpreter.node.expression.builtin.bool.False; -import org.enso.interpreter.node.expression.builtin.bool.True; +import org.enso.interpreter.node.expression.builtin.debug.Debug; import org.enso.interpreter.node.expression.builtin.meta.ProjectDescription; import org.enso.interpreter.node.expression.builtin.mutable.Array; import org.enso.interpreter.node.expression.builtin.mutable.Ref; @@ -34,7 +32,6 @@ import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; -import org.enso.interpreter.runtime.type.Constants; import org.enso.interpreter.runtime.type.TypesFromProxy; import org.enso.pkg.QualifiedName; @@ -54,41 +51,27 @@ public static class Debug { private final Map>> builtinMethodNodes; private final Map builtins; - @CompilerDirectives.CompilationFinal private AtomConstructor debug; - @CompilerDirectives.CompilationFinal private AtomConstructor projectDescription; - private final Error error; private final Module module; private final ModuleScope scope; public final Number number; + private final Bool bool; private final Ordering ordering; private final System system; private final Special special; // Builtin types - @CompilerDirectives.CompilationFinal private AtomConstructor any; - - @CompilerDirectives.CompilationFinal private AtomConstructor nothing; - - @CompilerDirectives.CompilationFinal private AtomConstructor function; - - @CompilerDirectives.CompilationFinal private AtomConstructor polyglot; - - @CompilerDirectives.CompilationFinal private AtomConstructor text; - - @CompilerDirectives.CompilationFinal private AtomConstructor array; - - @CompilerDirectives.CompilationFinal private AtomConstructor bool; - - @CompilerDirectives.CompilationFinal private AtomConstructor trueConstructor; - - @CompilerDirectives.CompilationFinal private AtomConstructor falseConstructor; - - @CompilerDirectives.CompilationFinal private AtomConstructor dataflowError; - - @CompilerDirectives.CompilationFinal private AtomConstructor ref; - - @CompilerDirectives.CompilationFinal private AtomConstructor managedResource; + private final BuiltinAtomConstructor any; + private final BuiltinAtomConstructor nothing; + private final BuiltinAtomConstructor function; + private final BuiltinAtomConstructor polyglot; + private final BuiltinAtomConstructor text; + private final BuiltinAtomConstructor array; + private final BuiltinAtomConstructor dataflowError; + private final BuiltinAtomConstructor ref; + private final BuiltinAtomConstructor managedResource; + private final BuiltinAtomConstructor debug; + private final BuiltinAtomConstructor projectDescription; /** * Creates an instance with builtin methods installed. @@ -109,6 +92,22 @@ public Builtins(Context context) { ordering = new Ordering(this); system = new System(this); number = new Number(this); + bool = new Bool(this); + + any = new BuiltinAtomConstructor(this, Any.class); + nothing = new BuiltinAtomConstructor(this, Nothing.class); + function = + new BuiltinAtomConstructor( + this, org.enso.interpreter.node.expression.builtin.function.Function.class); + polyglot = new BuiltinAtomConstructor(this, Polyglot.class); + text = new BuiltinAtomConstructor(this, Text.class); + array = new BuiltinAtomConstructor(this, Array.class); + dataflowError = + new BuiltinAtomConstructor(this, org.enso.interpreter.node.expression.builtin.Error.class); + ref = new BuiltinAtomConstructor(this, Ref.class); + managedResource = new BuiltinAtomConstructor(this, ManagedResource.class); + debug = new BuiltinAtomConstructor(this, Debug.class); + projectDescription = new BuiltinAtomConstructor(this, ProjectDescription.class); special = new Special(language); } @@ -335,11 +334,7 @@ public AtomConstructor getBuiltinType(String name) { * @return the {@code Nothing} atom constructor */ public AtomConstructor nothing() { - if (nothing == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - nothing = getBuiltinType(Nothing.class); - } - return nothing; + return nothing.constructor(); } /** @@ -348,11 +343,7 @@ public AtomConstructor nothing() { * @return the {@code Text} part of builtins. */ public AtomConstructor text() { - if (text == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - text = getBuiltinType(Text.class); - } - return text; + return text.constructor(); } /** @@ -361,12 +352,7 @@ public AtomConstructor text() { * @return the {@code Function} atom constructor */ public AtomConstructor function() { - if (function == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - function = - getBuiltinType(org.enso.interpreter.node.expression.builtin.function.Function.class); - } - return function; + return function.constructor(); } /** @@ -378,40 +364,14 @@ public Number number() { return number; } - /** @return the Boolean constructor. */ - public AtomConstructor bool() { - if (bool == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - bool = getBuiltinType(Boolean.class); - } + /** @return the container for boolean constructors. */ + public Bool bool() { return bool; } - /** @return the True constructor. */ - public AtomConstructor trueAtom() { - if (trueConstructor == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - trueConstructor = getBuiltinType(True.class); - } - return trueConstructor; - } - - /** @return the False constructor. */ - public AtomConstructor falseAtom() { - if (falseConstructor == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - falseConstructor = getBuiltinType(False.class); - } - return falseConstructor; - } - /** @return the ManagedResource constructor. */ public AtomConstructor managedResource() { - if (managedResource == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - managedResource = getBuiltinType(ManagedResource.class); - } - return managedResource; + return managedResource.constructor(); } /** @return the builtin Error types container. */ @@ -425,11 +385,7 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - if (any == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - any = getBuiltinType(Any.class); - } - return any; + return any.constructor(); } /** @@ -439,20 +395,12 @@ public AtomConstructor any() { * @return the {@code Debug} atom constructor */ public AtomConstructor debug() { - if (debug == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - debug = getBuiltinType(Debug.class); - } - return debug; + return debug.constructor(); } /** @return the {@code Project_Description} atom constructor */ public AtomConstructor getProjectDescription() { - if (projectDescription == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - projectDescription = getBuiltinType(ProjectDescription.class); - } - return projectDescription; + return projectDescription.constructor(); } /** @return the {@code System} atom constructor. */ @@ -462,29 +410,17 @@ public System system() { /** @return the Array constructor. */ public AtomConstructor array() { - if (array == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - array = getBuiltinType(Array.class); - } - return array; + return array.constructor(); } /** @return the Ref constructor. */ public AtomConstructor ref() { - if (ref == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - ref = getBuiltinType(Ref.class); - } - return ref; + return ref.constructor(); } /** @return the container for polyglot-related builtins. */ public AtomConstructor polyglot() { - if (polyglot == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - polyglot = getBuiltinType(Polyglot.class); - } - return polyglot; + return polyglot.constructor(); } /** @return the {@code Caught_Panic} atom constructor */ @@ -504,11 +440,7 @@ public Ordering ordering() { /** @return the container for the dataflow error-related builtins */ public AtomConstructor dataflowError() { - if (dataflowError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - dataflowError = getBuiltinType(org.enso.interpreter.node.expression.builtin.Error.class); - } - return dataflowError; + return dataflowError.constructor(); } public Special special() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/DataflowError.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/DataflowError.java deleted file mode 100644 index 4c69e6e2a449..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/DataflowError.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.error.CatchErrorMethodGen; -import org.enso.interpreter.node.expression.builtin.error.ErrorToTextMethodGen; -import org.enso.interpreter.node.expression.builtin.error.GetStackTraceTextMethodGen; -import org.enso.interpreter.node.expression.builtin.error.ThrowErrorMethodGen; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.scope.ModuleScope; - -public class DataflowError { - private final AtomConstructor error; - - public DataflowError(Language language, ModuleScope scope) { - error = new AtomConstructor("Error", scope).initializeFields(); - - scope.registerConstructor(error); - scope.registerMethod(error, "throw", ThrowErrorMethodGen.makeFunction(language)); - scope.registerMethod(error, "catch_primitive", CatchErrorMethodGen.makeFunction(language)); - scope.registerMethod( - error, "get_stack_trace_text", GetStackTraceTextMethodGen.makeFunction(language)); - scope.registerMethod(error, "to_text", ErrorToTextMethodGen.makeFunction(language)); - } - - public AtomConstructor constructor() { - return error; - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index 96ee794f5eac..018a635f2235 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java @@ -10,44 +10,29 @@ import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.text.Text; +import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; + /** Container for builtin Error types */ public class Error { - @CompilerDirectives.CompilationFinal private AtomConstructor syntaxError; - - @CompilerDirectives.CompilationFinal private AtomConstructor typeError; - - @CompilerDirectives.CompilationFinal private AtomConstructor compileError; - - @CompilerDirectives.CompilationFinal private AtomConstructor inexhaustivePatternMatchError; - - @CompilerDirectives.CompilationFinal private AtomConstructor uninitializedState; - - @CompilerDirectives.CompilationFinal private AtomConstructor noSuchMethodError; - - @CompilerDirectives.CompilationFinal private AtomConstructor noSuchConversionError; - - @CompilerDirectives.CompilationFinal private AtomConstructor polyglotError; - - @CompilerDirectives.CompilationFinal private AtomConstructor moduleNotInPackageError; - - @CompilerDirectives.CompilationFinal private AtomConstructor arithmeticError; - - @CompilerDirectives.CompilationFinal private AtomConstructor invalidArrayIndexError; - - @CompilerDirectives.CompilationFinal private AtomConstructor arityError; - - @CompilerDirectives.CompilationFinal private AtomConstructor unsupportedArgumentsError; - - @CompilerDirectives.CompilationFinal private AtomConstructor moduleDoesNotExistError; - - @CompilerDirectives.CompilationFinal private AtomConstructor notInvokableError; - - @CompilerDirectives.CompilationFinal private AtomConstructor invalidConversionTargetError; - - @CompilerDirectives.CompilationFinal private AtomConstructor panic; - - @CompilerDirectives.CompilationFinal private AtomConstructor caughtPanic; + private final BuiltinAtomConstructor syntaxError; + private final BuiltinAtomConstructor typeError; + private final BuiltinAtomConstructor compileError; + private final BuiltinAtomConstructor inexhaustivePatternMatchError; + private final BuiltinAtomConstructor uninitializedState; + private final BuiltinAtomConstructor noSuchMethodError; + private final BuiltinAtomConstructor noSuchConversionError; + private final BuiltinAtomConstructor polyglotError; + private final BuiltinAtomConstructor moduleNotInPackageError; + private final BuiltinAtomConstructor arithmeticError; + private final BuiltinAtomConstructor invalidArrayIndexError; + private final BuiltinAtomConstructor arityError; + private final BuiltinAtomConstructor unsupportedArgumentsError; + private final BuiltinAtomConstructor moduleDoesNotExistError; + private final BuiltinAtomConstructor notInvokableError; + private final BuiltinAtomConstructor invalidConversionTargetError; + private final BuiltinAtomConstructor panic; + private final BuiltinAtomConstructor caughtPanic; @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; @@ -56,66 +41,57 @@ public class Error { private static final Text shiftTooBigMessage = Text.create("Shift amount too large."); private static final Text divideByZeroMessage = Text.create("Cannot divide by zero."); - private final Builtins builtins; - + /** Creates builders for error Atom Constructors. */ public Error(Builtins builtins) { - this.builtins = builtins; + syntaxError = new BuiltinAtomConstructor(builtins, SyntaxError.class); + typeError = new BuiltinAtomConstructor(builtins, TypeError.class); + compileError = new BuiltinAtomConstructor(builtins, CompileError.class); + inexhaustivePatternMatchError = + new BuiltinAtomConstructor(builtins, InexhaustivePatternMatchError.class); + uninitializedState = new BuiltinAtomConstructor(builtins, UninitializedState.class); + noSuchMethodError = new BuiltinAtomConstructor(builtins, NoSuchMethodError.class); + noSuchConversionError = new BuiltinAtomConstructor(builtins, NoSuchConversionError.class); + polyglotError = new BuiltinAtomConstructor(builtins, PolyglotError.class); + moduleNotInPackageError = new BuiltinAtomConstructor(builtins, ModuleNotInPackageError.class); + arithmeticError = new BuiltinAtomConstructor(builtins, ArithmeticError.class); + invalidArrayIndexError = new BuiltinAtomConstructor(builtins, InvalidArrayIndexError.class); + arityError = new BuiltinAtomConstructor(builtins, ArityError.class); + unsupportedArgumentsError = + new BuiltinAtomConstructor(builtins, UnsupportedArgumentTypes.class); + moduleDoesNotExistError = new BuiltinAtomConstructor(builtins, ModuleDoesNotExist.class); + notInvokableError = new BuiltinAtomConstructor(builtins, NotInvokableError.class); + invalidConversionTargetError = + new BuiltinAtomConstructor(builtins, InvalidConversionTargetError.class); + panic = new BuiltinAtomConstructor(builtins, Panic.class); + caughtPanic = new BuiltinAtomConstructor(builtins, CaughtPanic.class); } public Atom makeSyntaxError(Object message) { - if (syntaxError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - syntaxError = builtins.getBuiltinType(SyntaxError.class); - } return syntaxError.newInstance(message); } public Atom makeCompileError(Object message) { - if (compileError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - compileError = builtins.getBuiltinType(CompileError.class); - } return compileError.newInstance(message); } public Atom makeInexhaustivePatternMatchError(Object message) { - if (inexhaustivePatternMatchError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - inexhaustivePatternMatchError = builtins.getBuiltinType(InexhaustivePatternMatchError.class); - } return inexhaustivePatternMatchError.newInstance(message); } public Atom makeUninitializedStateError(Object key) { - if (uninitializedState == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - uninitializedState = builtins.getBuiltinType(UninitializedState.class); - } return uninitializedState.newInstance(key); } public Atom makeModuleNotInPackageError() { - if (moduleNotInPackageError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - moduleNotInPackageError = builtins.getBuiltinType(ModuleNotInPackageError.class); - } return moduleNotInPackageError.newInstance(); } public AtomConstructor panic() { - if (panic == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - panic = builtins.getBuiltinType(Panic.class); - } - return panic; + return panic.constructor(); } public AtomConstructor caughtPanic() { - if (caughtPanic == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - caughtPanic = builtins.getBuiltinType(CaughtPanic.class); - } - return caughtPanic; + return caughtPanic.constructor(); } /** @@ -126,27 +102,15 @@ public AtomConstructor caughtPanic() { * @return a runtime representation of the error */ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { - if (noSuchMethodError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - noSuchMethodError = builtins.getBuiltinType(NoSuchMethodError.class); - } return noSuchMethodError.newInstance(target, symbol); } public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { - if (noSuchConversionError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - noSuchConversionError = builtins.getBuiltinType(NoSuchConversionError.class); - } return noSuchConversionError.newInstance(target, that, conversion); } public Atom makeInvalidConversionTargetError(Object target) { - if (invalidConversionTargetError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - invalidConversionTargetError = builtins.getBuiltinType(InvalidConversionTargetError.class); - } return invalidConversionTargetError.newInstance(target); } @@ -159,10 +123,6 @@ public Atom makeInvalidConversionTargetError(Object target) { * @return a runtime representation of the error. */ public Atom makeTypeError(Object expected, Object actual, String name) { - if (typeError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - typeError = builtins.getBuiltinType(TypeError.class); - } return typeError.newInstance(expected, actual, Text.create(name)); } @@ -173,10 +133,6 @@ public Atom makeTypeError(Object expected, Object actual, String name) { * @return a runtime representation of the polyglot error. */ public Atom makePolyglotError(Object cause) { - if (polyglotError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - polyglotError = builtins.getBuiltinType(PolyglotError.class); - } return polyglotError.newInstance(cause); } @@ -186,18 +142,14 @@ public Atom makePolyglotError(Object cause) { * @param reason the reason that the error is being thrown for * @return a runtime representation of the arithmetic error */ - public Atom makeArithmeticError(Text reason) { - if (arithmeticError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - arithmeticError = builtins.getBuiltinType(ArithmeticError.class); - } + private Atom makeArithmeticError(Text reason) { return arithmeticError.newInstance(reason); } /** @return An arithmetic error representing a too-large shift for the bit shift. */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); + transferToInterpreterAndInvalidate(); arithmeticErrorShiftTooBig = makeArithmeticError(shiftTooBigMessage); } return arithmeticErrorShiftTooBig; @@ -206,7 +158,7 @@ public Atom getShiftAmountTooLargeError() { /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); + transferToInterpreterAndInvalidate(); arithmeticErrorDivideByZero = makeArithmeticError(divideByZeroMessage); } return arithmeticErrorDivideByZero; @@ -218,10 +170,6 @@ public Atom getDivideByZeroError() { * @return An error representing that the {@code index} is not valid in {@code array} */ public Atom makeInvalidArrayIndexError(Object array, Object index) { - if (invalidArrayIndexError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - invalidArrayIndexError = builtins.getBuiltinType(InvalidArrayIndexError.class); - } return invalidArrayIndexError.newInstance(array, index); } @@ -232,10 +180,6 @@ public Atom makeInvalidArrayIndexError(Object array, Object index) { * @return an error informing about the arity being mismatched */ public Atom makeArityError(long expected_min, long expected_max, long actual) { - if (arityError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - arityError = builtins.getBuiltinType(ArityError.class); - } return arityError.newInstance(expected_min, expected_max, actual); } @@ -245,10 +189,6 @@ public Atom makeArityError(long expected_min, long expected_max, long actual) { * given method callp */ public Atom makeUnsupportedArgumentsError(Object[] args) { - if (unsupportedArgumentsError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - unsupportedArgumentsError = builtins.getBuiltinType(UnsupportedArgumentTypes.class); - } return unsupportedArgumentsError.newInstance(new Array(args)); } @@ -257,10 +197,6 @@ public Atom makeUnsupportedArgumentsError(Object[] args) { * @return a module does not exist error */ public Atom makeModuleDoesNotExistError(String name) { - if (moduleDoesNotExistError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - moduleDoesNotExistError = builtins.getBuiltinType(ModuleDoesNotExist.class); - } return moduleDoesNotExistError.newInstance(Text.create(name)); } @@ -269,10 +205,6 @@ public Atom makeModuleDoesNotExistError(String name) { * @return a not invokable error */ public Atom makeNotInvokableError(Object target) { - if (notInvokableError == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - notInvokableError = builtins.getBuiltinType(NotInvokableError.class); - } return notInvokableError.newInstance(target); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java index e7a565077581..acafb1ca1eba 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java @@ -12,71 +12,45 @@ /** A container for all number-related builtins. */ public class Number { - @CompilerDirectives.CompilationFinal private AtomConstructor smallInteger; + private final BuiltinAtomConstructor smallInteger; + private final BuiltinAtomConstructor bigInteger; + private final BuiltinAtomConstructor integer; + private final BuiltinAtomConstructor number; + private final BuiltinAtomConstructor decimal; - @CompilerDirectives.CompilationFinal private AtomConstructor bigInteger; - - @CompilerDirectives.CompilationFinal private AtomConstructor integer; - - @CompilerDirectives.CompilationFinal private AtomConstructor number; - - @CompilerDirectives.CompilationFinal private AtomConstructor decimal; - - private final Builtins builtins; - - /** - * Creates and registers number builtins. - * - * @param language the current language instance. - * @param scope the builtins scope. - */ + /** Creates builders for number Atom Constructors. */ public Number(Builtins builtins) { - this.builtins = builtins; + smallInteger = new BuiltinAtomConstructor(builtins, SmallInteger.class); + bigInteger = new BuiltinAtomConstructor(builtins, BigInteger.class); + integer = new BuiltinAtomConstructor(builtins, Integer.class); + number = + new BuiltinAtomConstructor( + builtins, org.enso.interpreter.node.expression.builtin.number.Number.class); + decimal = new BuiltinAtomConstructor(builtins, Decimal.class); } /** @return the Int64 atom constructor. */ public AtomConstructor getSmallInteger() { - if (smallInteger == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - smallInteger = builtins.getBuiltinType(SmallInteger.class); - } - return smallInteger; + return smallInteger.constructor(); } /** @return the Big_Integer atom constructor. */ public AtomConstructor getBigInteger() { - if (bigInteger == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - bigInteger = builtins.getBuiltinType(BigInteger.class); - } - return bigInteger; + return bigInteger.constructor(); } /** @return the Integer atom constructor */ public AtomConstructor getInteger() { - if (integer == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - integer = builtins.getBuiltinType(Integer.class); - } - return integer; + return integer.constructor(); } /** @return the Number atom constructor */ public AtomConstructor getNumber() { - if (number == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - number = - builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.number.Number.class); - } - return number; + return number.constructor(); } /** @return the Decimal atom constructor */ public AtomConstructor getDecimal() { - if (decimal == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - decimal = builtins.getBuiltinType(Decimal.class); - } - return decimal; + return decimal.constructor(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java index 6f9e6a5e5814..6360d8e8c0e1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java @@ -13,18 +13,18 @@ /** A container for builtin ordering types. */ public class Ordering { - @CompilerDirectives.CompilationFinal private AtomConstructor ordering; - - @CompilerDirectives.CompilationFinal private AtomConstructor less; - - @CompilerDirectives.CompilationFinal private AtomConstructor equal; - - @CompilerDirectives.CompilationFinal private AtomConstructor greater; - - @CompilerDirectives.CompilationFinal private Builtins builtins; + private final BuiltinAtomConstructor ordering; + private final BuiltinAtomConstructor less; + private final BuiltinAtomConstructor equal; + private final BuiltinAtomConstructor greater; public Ordering(Builtins builtins) { - this.builtins = builtins; + ordering = + new BuiltinAtomConstructor( + builtins, org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); + less = new BuiltinAtomConstructor(builtins, Less.class); + equal = new BuiltinAtomConstructor(builtins, Equal.class); + greater = new BuiltinAtomConstructor(builtins, Greater.class); } /** @@ -60,39 +60,21 @@ public Atom newGreater() { /** @return the Ordering constructor. */ public AtomConstructor ordering() { - if (ordering == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - ordering = - builtins.getBuiltinType( - org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); - } - return ordering; + return ordering.constructor(); } /** @return the Less constructor */ public AtomConstructor less() { - if (less == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - less = builtins.getBuiltinType(Less.class); - } - return less; + return less.constructor(); } /** @return the Equal constructor */ public AtomConstructor equal() { - if (equal == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - equal = builtins.getBuiltinType(Equal.class); - } - return equal; + return equal.constructor(); } /** @return the Greater constructor */ public AtomConstructor greater() { - if (greater == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - greater = builtins.getBuiltinType(Greater.class); - } - return greater; + return greater.constructor(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java index 4e1d16c64689..b57850cdcfc4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/System.java @@ -11,26 +11,15 @@ /** A container class for all System-related stdlib builtins. */ public class System { - private AtomConstructor system; - private AtomConstructor systemProcessResult; - private final Builtins builtins; + private final BuiltinAtomConstructor systemProcessResult; - /** - * Create and register all {@code System} constructors. - * - * @param language the current language instance. - * @param scope the scope to register constructors and methods in. - */ + /** Create builders for all {@code System} atom constructors. */ public System(Builtins builtins) { - this.builtins = builtins; + systemProcessResult = new BuiltinAtomConstructor(builtins, SystemProcessResult.class); } /** @return the atom constructor for {@code Process_Result}. */ public Atom makeSystemResult(Object exitCode, Object stdout, Object stderr) { - if (systemProcessResult == null) { - CompilerDirectives.transferToInterpreterAndInvalidate(); - systemProcessResult = builtins.getBuiltinType(SystemProcessResult.class); - } return systemProcessResult.newInstance(exitCode, stdout, stderr); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index dc6e3591bf8c..e3787e0c7790 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -63,7 +63,7 @@ public AtomConstructor(String name, ModuleScope definitionScope) { * @param definitionScope the scope in which this constructor was defined * @param builtin if true, the constructor refers to a builtin type (annotated with @BuiltinType */ - public AtomConstructor(String name, ModuleScope definitionScope, Boolean builtin) { + public AtomConstructor(String name, ModuleScope definitionScope, boolean builtin) { this.name = name; this.definitionScope = definitionScope; this.builtin = builtin; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java index a9ad2d43d427..ce7c7c83750a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java @@ -32,21 +32,21 @@ static class GetFunctionalDispatch { static Function resolveMethodOnPrimBoolean(UnresolvedSymbol symbol) { Context context = getContext(); Builtins builtins = context.getBuiltins(); - if (symbol.resolveFor(builtins.falseAtom()) != null) { + if (symbol.resolveFor(builtins.bool().getFalse()) != null) { return null; } - if (symbol.resolveFor(builtins.trueAtom()) != null) { + if (symbol.resolveFor(builtins.bool().getTrue()) != null) { return null; } - return symbol.resolveFor(builtins.bool(), context.getBuiltins().any()); + return symbol.resolveFor(builtins.bool().getBool(), context.getBuiltins().any()); } @CompilerDirectives.TruffleBoundary static Function resolveMethodOnBool(boolean self, UnresolvedSymbol symbol) { Context context = getContext(); Builtins builtins = context.getBuiltins(); - AtomConstructor cons = self ? builtins.trueAtom() : builtins.falseAtom(); - return symbol.resolveFor(cons, builtins.bool(), context.getBuiltins().any()); + AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); + return symbol.resolveFor(cons, builtins.bool().getBool(), context.getBuiltins().any()); } static Context getContext() { @@ -130,13 +130,13 @@ static Function resolveMethodOnPrimBoolean( AtomConstructor target, UnresolvedConversion conversion) { Context context = Context.get(null); Builtins builtins = context.getBuiltins(); - if (conversion.resolveFor(target, builtins.falseAtom()) != null) { + if (conversion.resolveFor(target, builtins.bool().getFalse()) != null) { return null; } - if (conversion.resolveFor(target, builtins.trueAtom()) != null) { + if (conversion.resolveFor(target, builtins.bool().getTrue()) != null) { return null; } - return conversion.resolveFor(target, builtins.bool(), context.getBuiltins().any()); + return conversion.resolveFor(target, builtins.bool().getBool(), context.getBuiltins().any()); } @CompilerDirectives.TruffleBoundary @@ -144,8 +144,9 @@ static Function resolveMethodOnBool( boolean self, AtomConstructor target, UnresolvedConversion conversion) { Context context = Context.get(null); Builtins builtins = context.getBuiltins(); - AtomConstructor cons = self ? builtins.trueAtom() : builtins.falseAtom(); - return conversion.resolveFor(target, cons, builtins.bool(), context.getBuiltins().any()); + AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); + return conversion.resolveFor( + target, cons, builtins.bool().getBool(), context.getBuiltins().any()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java index a33700213743..43353c792fba 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java @@ -32,7 +32,7 @@ public static Atom fromTypeSystem(Builtins builtins, String typeName) { case ConstantsGen.ARRAY: return builtins.array().newInstance(); case ConstantsGen.BOOLEAN: - return builtins.bool().newInstance(); + return builtins.bool().getBool().newInstance(); case ConstantsGen.DECIMAL: return builtins.number.getDecimal().newInstance(); case ConstantsGen.ERROR: diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index 67c1350116f8..54914c1e5d1c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -878,9 +878,9 @@ class IrToTruffle( runtimeConsOpt.map { atomCons => val any = context.getBuiltins.any val array = context.getBuiltins.array - val bool = context.getBuiltins.bool - val builtinTrue = context.getBuiltins.trueAtom - val builtinFalse = context.getBuiltins.falseAtom + val builtinBool = context.getBuiltins.bool().getBool + val builtinTrue = context.getBuiltins.bool().getTrue + val builtinFalse = context.getBuiltins.bool().getFalse val number = context.getBuiltins.number val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text @@ -889,9 +889,9 @@ class IrToTruffle( BooleanBranchNode.build(true, branchCodeNode.getCallTarget) } else if (atomCons == builtinFalse) { BooleanBranchNode.build(false, branchCodeNode.getCallTarget) - } else if (atomCons == bool) { + } else if (atomCons == builtinBool) { BooleanConstructorBranchNode.build( - bool, + builtinBool, builtinTrue, builtinFalse, branchCodeNode.getCallTarget From fe89bc1e37c6db19b209284488070ef4dc42217a Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 13:13:28 +0200 Subject: [PATCH 67/73] Add a requested compiler assert --- .../enso/interpreter/runtime/callable/atom/AtomConstructor.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index e3787e0c7790..dcedf8705e7d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java @@ -1,5 +1,6 @@ package org.enso.interpreter.runtime.callable.atom; +import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.RootCallTarget; import com.oracle.truffle.api.Truffle; @@ -82,6 +83,7 @@ public void setShadowDefinitions(ModuleScope scope) { // Ensure that synthetic methods, such as getters for fields are in the scope // Some scopes won't have any methods at this point, e.g., Nil or Nothing, hence the null // check. + CompilerAsserts.neverPartOfCompilation(); Map methods = this.definitionScope.getMethods().get(this); if (methods != null) { methods.forEach((name, fun) -> scope.registerMethod(this, name, fun)); From 6ba1bc446c68938b3e0798bab10a2d1997007791 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 15:33:10 +0200 Subject: [PATCH 68/73] Fix tests --- .../test/instrument/RuntimeServerTest.scala | 14 +++++++------- .../instrument/RuntimeVisualisationsTest.scala | 14 +++++++------- .../test/scala/org/enso/std/test/BooleanTest.scala | 4 ++-- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index b316f3bcb80e..ee64812fd097 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -110,11 +110,11 @@ class RuntimeServerTest val metadata = new Metadata - val idMainX = metadata.addItem(71, 1) - val idMainY = metadata.addItem(81, 7) - val idMainZ = metadata.addItem(97, 5) - val idFooY = metadata.addItem(136, 8) - val idFooZ = metadata.addItem(153, 5) + val idMainX = metadata.addItem(63, 1) + val idMainY = metadata.addItem(73, 7) + val idMainZ = metadata.addItem(89, 5) + val idFooY = metadata.addItem(128, 8) + val idFooZ = metadata.addItem(145, 5) def code = metadata.appendToCode( @@ -1027,7 +1027,7 @@ class RuntimeServerTest val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val idMain = context.Main.metadata.addItem(62, 47) + val idMain = context.Main.metadata.addItem(54, 47) val contents = context.Main.code val mainFile = context.writeMain(contents) @@ -1765,7 +1765,7 @@ class RuntimeServerTest val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() val moduleName = "Enso_Test.Test.Main" - val idMain = context.Main.metadata.addItem(62, 47) + val idMain = context.Main.metadata.addItem(54, 47) val mainFile = context.writeMain(context.Main.code) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 147b17c703ba..361ab203d4e8 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -110,7 +110,7 @@ class RuntimeVisualisationsTest val metadata = new Metadata val idMainX = metadata.addItem(63, 1) - val idMainY = metadata.addItem(83, 7) + val idMainY = metadata.addItem(73, 7) val idMainZ = metadata.addItem(89, 5) val idFooY = metadata.addItem(128, 8) val idFooZ = metadata.addItem(145, 5) @@ -248,7 +248,7 @@ class RuntimeVisualisationsTest } it should "emit visualisation update when expression is computed" in { - val idMainRes = context.Main.metadata.addItem(107, 1) + val idMainRes = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1227,7 +1227,7 @@ class RuntimeVisualisationsTest } it should "return ModuleNotFound error when attaching visualisation" in { - val idMain = context.Main.metadata.addItem(107, 1) + val idMain = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1287,7 +1287,7 @@ class RuntimeVisualisationsTest } it should "be able to use external libraries if they are needed by the visualisation" in { - val idMain = context.Main.metadata.addItem(107, 1) + val idMain = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1375,7 +1375,7 @@ class RuntimeVisualisationsTest } it should "return VisualisationExpressionFailed error when attaching visualisation" in { - val idMain = context.Main.metadata.addItem(107, 1) + val idMain = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1449,7 +1449,7 @@ class RuntimeVisualisationsTest } it should "return visualisation evaluation errors with diagnostic info" in { - val idMain = context.Main.metadata.addItem(107, 1) + val idMain = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1536,7 +1536,7 @@ class RuntimeVisualisationsTest } it should "return visualisation error with a stack trace" in { - val idMain = context.Main.metadata.addItem(107, 1) + val idMain = context.Main.metadata.addItem(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" diff --git a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala index 3e8bec70eabf..3cf820c771ea 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/BooleanTest.scala @@ -27,7 +27,7 @@ class BooleanTest extends InterpreterTest { """from Standard.Base.Data.Boolean import all |from Standard.Base.IO import all | - |Boolean.isTrue = this + |Boolean.Boolean.isTrue = this | |main = | true = 1 == 1 @@ -70,7 +70,7 @@ class BooleanTest extends InterpreterTest { val code = """from Standard.Base.Data.Boolean import all | - |Boolean.to_num = 2 + |Boolean.Boolean.to_num = 2 |True.to_num = 1 | |main = True.to_num + False.to_num From 4fde6ba20f660ae7c7b2233b10e251a94565e770 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Wed, 4 May 2022 17:31:17 +0200 Subject: [PATCH 69/73] Increase timeout to avoid FPs --- .../interpreter/test/instrument/InstrumentTestContext.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala index 8c8a49abcdc7..5c0abfda6d06 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -29,7 +29,7 @@ class InstrumentTestContext { } def receiveNIgnoreStdLib(n: Int): List[Api.Response] = { - receiveN(n + 1, 50).filter(excludeLibraryLoadingPayload) + receiveN(n + 1, 60).filter(excludeLibraryLoadingPayload) } private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = From b10bb8c8d65ad673906ad82c1786df4a8b0a6a38 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 5 May 2022 11:34:50 +0200 Subject: [PATCH 70/73] Turn on IR caches for tests Loading stdlib for `org.enso.interpreter.test.instrument.*` tests appears to be the main slowdown with builtins move. As in 25+ seconds vs 1 second, slowdown. Turning IR caching does not appear to affect the results and we are more or less back to what we used to have. --- .../enso/interpreter/test/instrument/RuntimeErrorsTest.scala | 2 +- .../interpreter/test/instrument/RuntimeInstrumentTest.scala | 2 +- .../enso/interpreter/test/instrument/RuntimeServerTest.scala | 2 +- .../enso/interpreter/test/instrument/RuntimeStdlibTest.scala | 2 +- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 2 +- .../interpreter/test/instrument/RuntimeVisualisationsTest.scala | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 386ec96bc1af..358c21087d2d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -61,7 +61,7 @@ class RuntimeErrorsTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index db98b1043ffc..66abe7bc3d8d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -54,7 +54,7 @@ class RuntimeInstrumentTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index ee64812fd097..68665457e7b1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -59,7 +59,7 @@ class RuntimeServerTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala index 61b979c28586..c6061529845e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala @@ -78,7 +78,7 @@ class RuntimeStdlibTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .out(out) .serverTransport(runtimeServerEmulator.makeServerTransport) .build() diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 0ad113234ee6..9304e3e8e9b9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -47,7 +47,7 @@ class RuntimeSuggestionUpdatesTest .option(RuntimeOptions.LOG_LEVEL, "WARNING") .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 361ab203d4e8..1ae098468c54 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -62,7 +62,7 @@ class RuntimeVisualisationsTest .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, "true") + .option(RuntimeOptions.DISABLE_IR_CACHES, "false") .option( RuntimeOptions.LANGUAGE_HOME_OVERRIDE, Paths.get("../../distribution/component").toFile.getAbsolutePath From aeeef1700695ce6ae0797d046cd56e2b65f2407a Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 5 May 2022 15:40:39 +0200 Subject: [PATCH 71/73] Fix tests --- .../Standard/Table/0.0.0-dev/src/Internal/Delimited_Reader.enso | 2 +- .../lib/Standard/Table/0.0.0-dev/src/Io/File_Format.enso | 2 +- .../org/enso/interpreter/node/expression/builtin/Boolean.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Reader.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Reader.enso index d2440e5e1208..1fc718e8b183 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Reader.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Reader.enso @@ -1,7 +1,7 @@ from Standard.Base import all import Standard.Table -import Standard.Base.Error.Extensions as Errors +import Standard.Base.Error.Common as Errors from Standard.Base.Error.Problem_Behavior as Problem_Behavior_Module import Problem_Behavior from Standard.Table.Error as Table_Errors import Invalid_Row, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows from Standard.Base.Data.Text.Encoding as Encoding_Module import Encoding diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Io/File_Format.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Io/File_Format.enso index cad8845b3aac..4079049b679d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Io/File_Format.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Io/File_Format.enso @@ -1,7 +1,7 @@ from Standard.Base import all import Standard.Table -import Standard.Base.Error.Extensions as Errors +import Standard.Base.Error.Common as Errors from Standard.Base.Error.Problem_Behavior as Problem_Behavior_Module import Problem_Behavior from Standard.Base.Data.Text.Encoding as Encoding_Module import Encoding import Standard.Table.Internal.Delimited_Reader diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java index 169885fda909..457a9c6492f2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -8,5 +8,5 @@ // The name Boolean would clash with java.lang.Boolean. // Before moving this definition to the `bool` package, as we should, one would have to address that // problem first. -@BuiltinType(name = "Standard.Base.Boolean.Boolean") +@BuiltinType(name = "Standard.Base.Data.Boolean.Boolean") public class Boolean extends Builtin {} From 6c0603227b31c97240e6554d869cc7e27a2c63d7 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 5 May 2022 16:11:17 +0200 Subject: [PATCH 72/73] Make disabling IR cache in tests configurable --- build.sbt | 2 +- .../interpreter/test/instrument/InstrumentTestContext.scala | 4 ++++ .../enso/interpreter/test/instrument/RuntimeErrorsTest.scala | 2 +- .../interpreter/test/instrument/RuntimeInstrumentTest.scala | 2 +- .../enso/interpreter/test/instrument/RuntimeServerTest.scala | 2 +- .../enso/interpreter/test/instrument/RuntimeStdlibTest.scala | 2 +- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 2 +- .../test/instrument/RuntimeVisualisationsTest.scala | 2 +- 8 files changed, 11 insertions(+), 7 deletions(-) diff --git a/build.sbt b/build.sbt index a82279232c68..86a8e902e462 100644 --- a/build.sbt +++ b/build.sbt @@ -1174,7 +1174,7 @@ lazy val runtime = (project in file("engine/runtime")) s"--upgrade-module-path=${file("engine/runtime/build-cache/truffle-api.jar").absolutePath}" ), Test / fork := true, - Test / envVars ++= distributionEnvironmentOverrides, + Test / envVars ++= distributionEnvironmentOverrides ++ Map("ENSO_TEST_DISABLE_IR_CACHE" -> "false"), bootstrap := CopyTruffleJAR.bootstrapJARs.value, Global / onLoad := EnvironmentCheck.addVersionCheck( graalVersion, diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala index 5c0abfda6d06..f51cfa4fa510 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -41,3 +41,7 @@ class InstrumentTestContext { } } + +object InstrumentTestContext { + val DISABLE_IR_CACHE = Option(System.getenv("ENSO_TEST_DISABLE_IR_CACHE")).getOrElse("true") +} diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 358c21087d2d..00e8b58ff054 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -61,7 +61,7 @@ class RuntimeErrorsTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 66abe7bc3d8d..6e297b367a72 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -54,7 +54,7 @@ class RuntimeInstrumentTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 68665457e7b1..03164b4ebcd9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -59,7 +59,7 @@ class RuntimeServerTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala index c6061529845e..74157f297789 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala @@ -78,7 +78,7 @@ class RuntimeStdlibTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .out(out) .serverTransport(runtimeServerEmulator.makeServerTransport) .build() diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 9304e3e8e9b9..0d0583d3b561 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -47,7 +47,7 @@ class RuntimeSuggestionUpdatesTest .option(RuntimeOptions.LOG_LEVEL, "WARNING") .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 1ae098468c54..181130e5dc58 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -62,7 +62,7 @@ class RuntimeVisualisationsTest .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, "false") + .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) .option( RuntimeOptions.LANGUAGE_HOME_OVERRIDE, Paths.get("../../distribution/component").toFile.getAbsolutePath From c90836dea2791b34df95d91004e8bad48c15dec7 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 5 May 2022 17:37:46 +0200 Subject: [PATCH 73/73] More formatting --- .../interpreter/test/instrument/InstrumentTestContext.scala | 3 ++- .../enso/interpreter/test/instrument/RuntimeErrorsTest.scala | 5 ++++- .../interpreter/test/instrument/RuntimeInstrumentTest.scala | 5 ++++- .../enso/interpreter/test/instrument/RuntimeServerTest.scala | 5 ++++- .../enso/interpreter/test/instrument/RuntimeStdlibTest.scala | 5 ++++- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 5 ++++- .../test/instrument/RuntimeVisualisationsTest.scala | 5 ++++- 7 files changed, 26 insertions(+), 7 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala index f51cfa4fa510..b49cd1d89384 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -43,5 +43,6 @@ class InstrumentTestContext { } object InstrumentTestContext { - val DISABLE_IR_CACHE = Option(System.getenv("ENSO_TEST_DISABLE_IR_CACHE")).getOrElse("true") + val DISABLE_IR_CACHE = + Option(System.getenv("ENSO_TEST_DISABLE_IR_CACHE")).getOrElse("true") } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 00e8b58ff054..e4585d0c960a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -61,7 +61,10 @@ class RuntimeErrorsTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala index 6e297b367a72..42826be77ea9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeInstrumentTest.scala @@ -54,7 +54,10 @@ class RuntimeInstrumentTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index 03164b4ebcd9..d9c6715b766a 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -59,7 +59,10 @@ class RuntimeServerTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_PROJECT_SUGGESTIONS, "false") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala index 74157f297789..8e1dc43a63c2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala @@ -78,7 +78,10 @@ class RuntimeStdlibTest .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .out(out) .serverTransport(runtimeServerEmulator.makeServerTransport) .build() diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 0d0583d3b561..4285fcb162a8 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -47,7 +47,10 @@ class RuntimeSuggestionUpdatesTest .option(RuntimeOptions.LOG_LEVEL, "WARNING") .option(RuntimeOptions.INTERPRETER_SEQUENTIAL_COMMAND_EXECUTION, "true") .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 181130e5dc58..4887ab62c261 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala @@ -62,7 +62,10 @@ class RuntimeVisualisationsTest .option(RuntimeOptions.ENABLE_GLOBAL_SUGGESTIONS, "false") .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") - .option(RuntimeOptions.DISABLE_IR_CACHES, InstrumentTestContext.DISABLE_IR_CACHE) + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option( RuntimeOptions.LANGUAGE_HOME_OVERRIDE, Paths.get("../../distribution/component").toFile.getAbsolutePath