From 4bbabc00be48b305927b455681419ed39ee550cc Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Thu, 5 May 2022 20:18:06 +0200 Subject: [PATCH] Move Builtin Types and Methods to stdlib (#3363) This PR replaces hard-coded `@Builtin_Method` and `@Builtin_Type` nodes in Builtins with an automated solution that a) collects metadata from such annotations b) generates `BuiltinTypes` c) registers builtin methods with corresponding constructors. The main differences are: 1) The owner of the builtin method does not necessarily have to be a builtin type 2) You can now mix regular methods and builtin ones in stdlib 3) No need to keep track of builtin methods and types in various places and register them by hand (a source of many typos or omissions as it found during the process of this PR) Related to #181497846 Benchmarks also execute within the margin of error. ### Important Notes The PR got a bit large over time as I was moving various builtin types and finding various corner cases. Most of the changes however are rather simple c&p from Builtins.enso to the corresponding stdlib module. Here is the list of the most crucial updates: - `engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java` - the core of the changes. We no longer register individual builtin constructors and their methods by hand. Instead, the information about those is read from 2 metadata files generated by annotation processors. When the builtin method is encountered in stdlib, we do not ignore the method. Instead we lookup it up in the list of registered functions (see `getBuiltinFunction` and `IrToTruffle`) - `engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java` has now information whether it corresponds to the builtin type or not. - `engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala` - when runtime stubs generator encounters a builtin type, based on the @Builtin_Type annotation, it looks up an existing constructor for it and registers it in the provided scope, rather than creating a new one. The scope of the constructor is also changed to the one coming from stdlib, while ensuring that synthetic methods (for fields) also get assigned correctly - `engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala` - when a builtin method is encountered in stdlib we don't generate a new function node for it, instead we look it up in the list of registered builtin methods. Note that Integer and Number present a bit of a challenge because they list a whole bunch of methods that don't have a corresponding method (instead delegating to small/big integer implementations). During the translation new atom constructors get initialized but we don't want to do it for builtins which have gone through the process earlier, hence the exception - `lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java` - @Builtin_Method processor not only generates the actual code fpr nodes but also collects and writes the info about them (name, class, params) to a metadata file that is read during builtins initialization - `lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/MethodProcessor.java` - @Builtin_Method processor no longer generates only (root) nodes but also collects and writes the info about them (name, class, params) to a metadata file that is read during builtins initialization - `lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java` - Similar to MethodProcessor but handles @Builtin_Type annotations. It doesn't, **yet**, generate any builtin objects. It also collects the names, as present in stdlib, if any, so that we can generate the names automatically (see generated `types/ConstantsGen.java`) - `engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin` - various classes annotated with @BuiltinType to ensure that the atom constructor is always properly registered for the builitn. Note that in order to support types fields in those, annotation takes optional `params` parameter (comma separated). - `engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala` - drop manual creation of test list which seemed to be a relict of the old design --- CHANGELOG.md | 2 + .../controller/searcher/action/hardcoded.rs | 10 +- .../native/inc/error_preprocessor.enso | 6 +- build.sbt | 8 +- .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 383 +++ .../0.0.0-dev/src/Data/Any/Extensions.enso | 343 --- .../Base/0.0.0-dev/src/Data/Array.enso | 179 ++ .../0.0.0-dev/src/Data/Array/Extensions.enso | 18 - .../Base/0.0.0-dev/src/Data/Boolean.enso | 114 + .../0.0.0-dev/src/Data/Json/Internal.enso | 4 +- .../Base/0.0.0-dev/src/Data/List.enso | 23 +- .../0.0.0-dev/src/Data/Noise/Generator.enso | 1 - .../0.0.0-dev/src/Data/Number/Extensions.enso | 316 --- .../Base/0.0.0-dev/src/Data/Numbers.enso | 1035 ++++++++ .../Base/0.0.0-dev/src/Data/Ordering.enso | 21 +- .../Standard/Base/0.0.0-dev/src/Data/Ref.enso | 43 + .../Base/0.0.0-dev/src/Data/Text.enso | 49 + .../0.0.0-dev/src/Data/Text/Extensions.enso | 3 - .../src/Data/Text/Prim_Text_Helper.enso | 7 + .../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 | 6 +- .../0.0.0-dev/src/Data/Time/Duration.enso | 1 + .../Base/0.0.0-dev/src/Data/Vector.enso | 3 +- .../Base/0.0.0-dev/src/Error/Common.enso | 527 ++++ .../Base/0.0.0-dev/src/Error/Extensions.enso | 268 -- .../Standard/Base/0.0.0-dev/src/Function.enso | 9 + .../lib/Standard/Base/0.0.0-dev/src/IO.enso | 36 + .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 45 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 406 +++- .../Base/0.0.0-dev/src/Meta/Enso_Project.enso | 62 +- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 7 + .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 105 + .../Base/0.0.0-dev/src/Polyglot/Java.enso | 40 +- .../Standard/Base/0.0.0-dev/src/Runtime.enso | 92 + .../Base/0.0.0-dev/src/Runtime/Debug.enso | 33 + .../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 | 58 + .../Base/0.0.0-dev/src/System/File.enso | 29 +- .../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 | 35 + .../0.0.0-dev/src/Connection/Connection.enso | 2 + .../Database/0.0.0-dev/src/Data/Dialect.enso | 2 +- .../Standard/Searcher/0.0.0-dev/src/Main.enso | 2 - .../src/Internal/Delimited_Reader.enso | 2 +- .../src/Internal/Unique_Name_Strategy.enso | 1 + .../src/Internal/Vector_Builder.enso | 2 - .../Table/0.0.0-dev/src/Io/File_Format.enso | 2 +- .../Standard/Test/0.0.0-dev/src/Bench.enso | 1 + .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 4 +- .../0.0.0-dev/src/Sql/Visualization.enso | 8 +- docs/runtime-roadmap.md | 2 +- .../search/DocSectionsBuilderTest.scala | 6 +- .../enso/launcher/upgrade/UpgradeSpec.scala | 2 +- .../fixtures/semantic/AtomFixtures.scala | 53 +- .../fixtures/semantic/CallableFixtures.scala | 2 +- .../fixtures/semantic/RecursionFixtures.scala | 9 +- .../callable/resolver/BaseResolverNode.java | 2 +- .../BooleanConstructorBranchNode.java | 21 +- .../node/controlflow/caseexpr/CaseNode.java | 7 +- .../node/expression/builtin/Any.java | 6 + .../node/expression/builtin/Boolean.java | 12 + .../node/expression/builtin/Builtin.java | 4 + .../node/expression/builtin/Error.java | 6 + .../node/expression/builtin/Nothing.java | 6 + .../node/expression/builtin/Polyglot.java | 6 + .../node/expression/builtin/bool/False.java | 7 + .../node/expression/builtin/bool/True.java | 7 + .../node/expression/builtin/debug/Debug.java | 7 + .../builtin/error/ArithmeticError.java | 7 + .../expression/builtin/error/ArityError.java | 7 + .../expression/builtin/error/CaughtPanic.java | 7 + .../builtin/error/CompileError.java | 7 + .../error/InexhaustivePatternMatchError.java | 7 + .../builtin/error/InvalidArrayIndexError.java | 7 + .../error/InvalidConversionTargetError.java | 7 + .../builtin/error/ModuleDoesNotExist.java | 7 + .../error/ModuleNotInPackageError.java | 7 + .../builtin/error/NoSuchConversionError.java | 7 + .../builtin/error/NoSuchMethodError.java | 7 + .../builtin/error/NotInvokableError.java | 7 + .../node/expression/builtin/error/Panic.java | 7 + .../builtin/error/PolyglotError.java | 7 + .../expression/builtin/error/SyntaxError.java | 7 + .../expression/builtin/error/TypeError.java | 7 + .../builtin/error/UninitializedState.java | 7 + .../error/UnsupportedArgumentTypes.java | 7 + ...oSuchConversionErrorToDisplayTextNode.java | 2 +- .../expression/builtin/function/Function.java | 7 + .../interop/generic/GetArraySizeNode.java | 2 +- .../expression/builtin/io/GetCwdNode.java | 2 +- .../expression/builtin/io/GetFileNode.java | 2 +- .../builtin/io/GetUserHomeNode.java | 2 +- .../builtin/meta/GetSourceLocationNode.java | 2 +- .../builtin/meta/ProjectDescription.java | 7 + .../expression/builtin/mutable/Array.java | 7 + .../expression/builtin/mutable/CopyNode.java | 2 +- .../node/expression/builtin/mutable/Ref.java | 7 + .../expression/builtin/number/BigInteger.java | 7 + .../expression/builtin/number/Decimal.java | 7 + .../expression/builtin/number/Integer.java | 7 + .../expression/builtin/number/Number.java | 7 + .../builtin/number/SmallInteger.java | 7 + .../number/bigInteger/BitShiftNode.java | 6 +- .../builtin/number/smallInteger/AbsNode.java | 2 +- .../number/smallInteger/BitShiftNode.java | 6 +- .../number/smallInteger/ToDecimalNode.java | 2 +- .../expression/builtin/ordering/Equal.java | 8 + .../expression/builtin/ordering/Greater.java | 8 + .../expression/builtin/ordering/Less.java | 8 + .../expression/builtin/ordering/Ordering.java | 8 + .../builtin/resource/ManagedResource.java | 7 + .../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 +- .../builtin/state/GetStateNode.java | 6 +- .../builtin/state/PutStateNode.java | 4 +- .../builtin/system/CreateProcessNode.java | 5 +- .../builtin/system/SystemProcessResult.java | 7 + .../builtin/text/PrimTextHelper.java | 7 + .../node/expression/builtin/text/Text.java | 7 + .../builtin/text/util/ExpectStringNode.java | 2 +- .../builtin/text/util/ExpectTextNode.java | 2 +- .../expression/constant/ConstructorNode.java | 6 +- .../expression/constant/EnsoProjectNode.java | 2 +- .../org/enso/interpreter/runtime/Module.java | 13 +- .../interpreter/runtime/builtin/Bool.java | 41 +- .../builtin/BuiltinAtomConstructor.java | 32 + .../interpreter/runtime/builtin/Builtins.java | 495 ++-- .../runtime/builtin/DataflowError.java | 28 - .../interpreter/runtime/builtin/Error.java | 264 +- .../interpreter/runtime/builtin/Meta.java | 60 - .../interpreter/runtime/builtin/Mutable.java | 51 - .../interpreter/runtime/builtin/Number.java | 405 +--- .../interpreter/runtime/builtin/Ordering.java | 44 +- .../interpreter/runtime/builtin/Polyglot.java | 46 - .../interpreter/runtime/builtin/Resource.java | 34 - .../interpreter/runtime/builtin/System.java | 43 +- .../interpreter/runtime/builtin/Text.java | 34 - .../interpreter/runtime/builtin/Warning.java | 22 - .../runtime/callable/atom/Atom.java | 2 +- .../callable/atom/AtomConstructor.java | 45 +- .../enso/interpreter/runtime/data/Array.java | 5 +- .../interpreter/runtime/data/text/Text.java | 4 +- .../runtime/error/DataflowError.java | 2 +- .../dispatch/DefaultBooleanExports.java | 31 +- .../runtime/scope/ModuleScope.java | 6 +- .../interpreter/runtime/type/Constants.java | 16 +- .../enso/interpreter/runtime/type/Types.java | 53 +- .../runtime/type/TypesFromProxy.java | 60 + .../error/FailedToApplyEditsException.java | 2 +- .../runtime/src/main/resources/Builtins.enso | 2159 ----------------- .../scala/org/enso/compiler/Compiler.scala | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 153 +- .../codegen/RuntimeStubsGenerator.scala | 17 +- .../compiler/context/SuggestionBuilder.scala | 3 +- .../scala/org/enso/compiler/core/IR.scala | 11 + .../org/enso/compiler/data/BindingsMap.scala | 8 +- .../pass/analyse/BindingAnalysis.scala | 13 +- .../compiler/pass/desugar/ComplexType.scala | 10 +- .../compiler/pass/lint/UnusedBindings.scala | 37 +- .../test/resources/Cycle_Test/src/Main.enso | 2 +- .../TestNonImportedOverloads/src/Main.enso | 2 +- .../TestNonImportedOverloads/src/Util.enso | 2 +- .../TestNonImportedOwnMethods/src/Main.enso | 2 +- .../TestNonImportedOwnMethods/src/Util.enso | 2 +- .../instrument/InstrumentTestContext.scala | 48 + .../test/instrument/ReplTest.scala | 31 +- .../test/instrument/RuntimeErrorsTest.scala | 226 +- .../instrument/RuntimeInstrumentTest.scala | 281 +-- .../test/instrument/RuntimeServerTest.scala | 541 ++--- .../test/instrument/RuntimeStdlibTest.scala | 5 +- .../RuntimeSuggestionUpdatesTest.scala | 147 +- .../RuntimeVisualisationsTest.scala | 189 +- .../test/instrument/TestMessages.scala | 6 +- .../interpreter/test/semantic/CaseTest.scala | 4 +- .../test/semantic/CodeLocationsTest.scala | 47 +- .../semantic/CompileDiagnosticsTest.scala | 10 +- .../ComplexTypeDefinitionSugarTest.scala | 2 +- .../test/semantic/ConstructorsTest.scala | 13 +- .../test/semantic/CurryingTest.scala | 2 +- .../test/semantic/DataflowErrorsTest.scala | 49 +- .../interpreter/test/semantic/DateTest.scala | 10 +- .../interpreter/test/semantic/EvalTest.scala | 15 +- .../test/semantic/ExpressionIdTest.scala | 27 +- .../test/semantic/FunctionSugarTest.scala | 2 +- .../test/semantic/GlobalScopeTest.scala | 10 +- .../test/semantic/GroupingTest.scala | 2 +- .../test/semantic/InteropTest.scala | 9 +- .../test/semantic/JavaInteropTest.scala | 2 - .../test/semantic/LambdaChainingTest.scala | 2 +- .../semantic/LambdaShorthandArgsTest.scala | 10 +- .../test/semantic/LambdaTest.scala | 8 +- .../test/semantic/MethodsTest.scala | 33 +- .../test/semantic/NamedArgumentsTest.scala | 26 +- .../OverloadsResolutionErrorTest.scala | 2 +- .../test/semantic/PanicsTest.scala | 6 +- .../test/semantic/PatternMatchTest.scala | 18 +- .../test/semantic/PolyglotTest.scala | 74 +- .../test/semantic/RuntimeManagementTest.scala | 15 +- .../interpreter/test/semantic/StateTest.scala | 25 +- .../semantic/SuspendedArgumentsTest.scala | 8 +- .../test/semantic/SystemProcessTest.scala | 96 +- .../interpreter/test/semantic/TextTest.scala | 20 +- .../scala/org/enso/std/test/BooleanTest.scala | 22 +- .../scala/org/enso/std/test/NumberTest.scala | 2 +- .../enso/interpreter/dsl/BuiltinMethod.java | 3 + .../org/enso/interpreter/dsl/BuiltinType.java | 22 + .../dsl/BuiltinsMetadataProcessor.java | 124 + .../enso/interpreter/dsl/MethodProcessor.java | 71 +- .../enso/interpreter/dsl/TypeProcessor.java | 169 ++ .../dsl/model/MethodDefinition.java | 24 + test/Benchmarks/src/Collections.enso | 1 - test/Benchmarks/src/Main.enso | 2 + test/Benchmarks/src/Text/Build.enso | 3 +- test/Tests/src/Data/Array_Spec.enso | 8 + test/Tests/src/Data/Bool_Spec.enso | 6 + test/Tests/src/Data/List_Spec.enso | 1 + test/Tests/src/Data/Noise/Generator_Spec.enso | 4 +- test/Tests/src/Data/Numbers_Spec.enso | 2 +- test/Tests/src/Data/Ref_Spec.enso | 12 + test/Tests/src/Resource/Bracket_Spec.enso | 1 + test/Tests/src/Semantic/Case_Spec.enso | 3 +- test/Tests/src/Semantic/Meta_Spec.enso | 6 +- .../src/Semantic/Python_Interop_Spec.enso | 2 + test/Tests/src/Semantic/Runtime_Spec.enso | 3 +- test/Tests/src/System/Process_Spec.enso | 2 + test/Visualization_Tests/src/Sql_Spec.enso | 4 +- tools/ci/Test.enso | 2 +- 236 files changed, 6131 insertions(+), 5688 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 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 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso 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/Numbers.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Prim_Text_Helper.enso delete mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso 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/IO.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso create mode 100644 distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso 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/Any.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java 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/Polyglot.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/debug/Debug.java 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/function/Function.java 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/mutable/Array.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java 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 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/node/expression/builtin/text/PrimTextHelper.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java 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 delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Polyglot.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Resource.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Text.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Warning.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java delete mode 100644 engine/runtime/src/main/resources/Builtins.enso create mode 100644 engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala 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/BuiltinsMetadataProcessor.java create mode 100644 lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java create mode 100644 test/Tests/src/Data/Ref_Spec.enso diff --git a/CHANGELOG.md b/CHANGELOG.md index f3ebc9300aca..d53cbcb9d53e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -191,6 +191,7 @@ - [Provide `tagValues` for function arguments in the language server][3422] - [Delay construction of Truffle nodes to speed initialization][3429] - [Frgaal compiler integration to allow for latest Java constructs][3421] +- [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 @@ -206,6 +207,7 @@ [3422]: https://github.com/enso-org/enso/pull/3422 [3429]: https://github.com/enso-org/enso/pull/3429 [3421]: https://github.com/enso-org/enso/pull/3421 +[3363]: https://github.com/enso-org/enso/pull/3363 # Enso 2.0.0-alpha.18 (2021-10-12) diff --git a/app/gui/src/controller/searcher/action/hardcoded.rs b/app/gui/src/controller/searcher/action/hardcoded.rs index 609f2740ac1f..83d28c0608fa 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.Numbers.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.Numbers.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/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/build.sbt b/build.sbt index 7454486ed32a..86a8e902e462 100644 --- a/build.sbt +++ b/build.sbt @@ -950,7 +950,10 @@ lazy val searcher = project lazy val `interpreter-dsl` = (project in file("lib/scala/interpreter-dsl")) .settings( version := "0.1", - libraryDependencies += "org.netbeans.api" % "org-openide-util-lookup" % "RELEASE130" + libraryDependencies ++= Seq( + "org.apache.commons" % "commons-lang3" % commonsLangVersion, + "org.netbeans.api" % "org-openide-util-lookup" % "RELEASE130" + ) ) // ============================================================================ @@ -1130,6 +1133,7 @@ lazy val runtime = (project in file("engine/runtime")) Compile/compile/compilers := FrgaalJavaCompiler.compilers((Compile / dependencyClasspath).value, compilers.value, javaVersion), 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( @@ -1170,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/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..b41e85165333 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -0,0 +1,383 @@ +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" + + ## 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`. + + 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/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/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 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..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,5 +1,7 @@ from Standard.Base import all hiding Number, Boolean, Array +import Standard.Base.Data.Numbers 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 f28e03968131..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,5 +1,8 @@ -from Standard.Builtins import all -from Standard.Builtins export Nil, Cons +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 +import Standard.Base.Runtime.Unsafe ## The basic cons-list type. @@ -11,9 +14,18 @@ from Standard.Builtins export Nil, Cons > 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. + type Nil + + ## A cons cell for a cons list. + + Arguments: + - 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. @@ -264,7 +276,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 @@ -364,4 +376,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/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/Number/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso deleted file mode 100644 index ce6a7c2a10b8..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Number/Extensions.enso +++ /dev/null @@ -1,316 +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 - -## 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 - -## Returns the sign of the number. -Number.signum : Integer -Number.signum = - if this > 0 then 1 else - if this < 0 then -1 else 0 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso new file mode 100644 index 000000000000..f235e6902990 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso @@ -0,0 +1,1035 @@ +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,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 + 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 + + ## Returns the sign of the number. + signum : Integer + signum = + if this > 0 then 1 else + if this < 0 then -1 else 0 + + +## 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./" + + ## 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. + + > Example + Computing the remainder when dividing 3.5 by 2. + + 3.5 % 2 == 1.5 + + > Example + Computing the fractional part of a number. + + 10.5 % 1.0 == 0.5 + % : Number -> Number ! Arithmetic_Error + % 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) + +## 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 an increasing 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 = case n of + Integer -> Range.Range this n + _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") + + ## ALIAS Range + + Creates a decreasing right-exclusive range of integers from `this` to `n`. + + Arguments: + - n: The end of the range. + + > Example + Create a range containing the numbers 5, 4, 3, 2, 1. + + 5.down_to 0 + down_to : Integer -> Range + down_to n = case n of + Integer -> Range.Range this n -1 + _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") + + ## 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/Data/Ordering.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering.enso index 8810b4dfd88f..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 @@ -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,18 @@ 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 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/Ref.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso new file mode 100644 index 000000000000..f9c66d07131e --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ref.enso @@ -0,0 +1,43 @@ +## Utilities for working with mutable references. +type Ref + + ## A mutable reference type. + @Builtin_Type + type Ref + +## 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" 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 new file mode 100644 index 000000000000..022a39f9412c --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -0,0 +1,49 @@ +import Standard.Base.Meta +polyglot java import org.enso.base.Text_Utils + +## 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.+" + + ## 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 b2e2e5ff4aa7..cfc66e4ad11b 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 @@ -16,8 +15,6 @@ from Standard.Base.Error.Problem_Behavior as Problem_Behavior_Module import Prob 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/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..c8ad1ea9cbf4 --- /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" 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 00ef98632ed8..b0c1c160a725 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 @@ -14,8 +14,6 @@ import Standard.Base.Data.Text.Regex.Mode import Standard.Base.Data.Text.Regex.Option 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 8d1c548e9301..5e537bcc02f3 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 @@ -40,13 +40,9 @@ 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.Data.Text.Matching_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 polyglot java import java.lang.IndexOutOfBoundsException polyglot java import java.lang.StringBuffer 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 9b92389b10c0..467ec8edde3c 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,6 +1,5 @@ from Standard.Base import all -from Standard.Builtins import Array -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 02dee47260dd..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 @@ -1,4 +1,154 @@ from Standard.Base import all +import Standard.Base.Data.Json +import Standard.Base.Runtime + +## 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 Runtime.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 @@ -33,3 +183,380 @@ 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 Runtime.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 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.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. + - name: The name of the argument whose type is mismatched. +@Builtin_Type +type Type_Error expected actual name + +## 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_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_min expected_max 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.Common as Errors + + 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 7a628a9a5043..000000000000 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Extensions.enso +++ /dev/null @@ -1,268 +0,0 @@ -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) - -## 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 - - 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 - -## 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. - - 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 Builtins.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/Function.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso new file mode 100644 index 000000000000..4a478a005f84 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso @@ -0,0 +1,9 @@ +# 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 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..24b01bd0ba29 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/IO.enso @@ -0,0 +1,36 @@ +## Builtin IO operations. + +## 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/Main.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Main.enso index e0b17543a842..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 @@ -1,5 +1,6 @@ -import project.Data.Any.Extensions -import project.Data.Array.Extensions +import project.Data.Any +import project.Data.Array +import project.Data.Boolean import project.Data.Interval import project.Data.Json import project.Data.List @@ -7,28 +8,34 @@ import project.Data.Locale import project.Data.Map import project.Data.Maybe import project.Data.Noise -import project.Data.Number.Extensions +import project.Data.Numbers 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 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 +import project.Nothing import project.Math 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 import project.Warning -from Standard.Builtins import Nothing, Number, Integer, Any, True, False, Cons, Boolean, Arithmetic_Error - export project.Data.Interval export project.Data.Json export project.Data.Locale @@ -36,21 +43,27 @@ 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.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 export project.Warning -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.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.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 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 @@ -60,11 +73,11 @@ from project.Data.Range export Range https://www.pivotaltracker.com/story/show/181309938 from project.Data.Text.Extensions export Text, Line_Ending_Style, Case, Location 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.Polyglot.Java export all +from project.Nothing 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 project.Runtime.Resource 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 52919c6bfcc9..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,6 +1,233 @@ from Standard.Base import all -import Standard.Builtins +## 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 +237,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 +253,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 +305,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 +317,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 +355,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 +426,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 +435,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 +444,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/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 new file mode 100644 index 000000000000..9b24da3a2528 --- /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 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..43c03bc0404b --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -0,0 +1,105 @@ +## 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: + - 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 "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. +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" + +## 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/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.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso new file mode 100644 index 000000000000..529f07434cd6 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -0,0 +1,92 @@ +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. + +## 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 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..473b06f5a1ef --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Debug.enso @@ -0,0 +1,33 @@ +## Debug utilities. + +## 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..b7db4c23f562 --- /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" 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..633a4e2e5a33 --- /dev/null +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso @@ -0,0 +1,58 @@ +## Functionality for interacting with the host 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 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 1b64f6d80ead..f68fe8d7a40b 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 @@ -5,6 +5,7 @@ import Standard.Base.Data.Text.Matching_Mode import Standard.Base.Data.Text.Text_Sub_Range from Standard.Base.Data.Text.Encoding as Encoding_Module import Encoding from Standard.Base.Error.Problem_Behavior as Problem_Behavior_Module import Problem_Behavior, Report_Warning +from Standard.Base.Runtime.Resource import all export Standard.Base.System.File.Option @@ -32,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. @@ -129,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 @@ -142,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. @@ -952,3 +953,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/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 495c7f48e685..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 @@ -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 @@ -188,3 +189,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 + + ## PRIVATE + 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/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/Database/0.0.0-dev/src/Data/Dialect.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect.enso index 48cf0d582033..547f6a3ae5b2 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,6 @@ from Standard.Base import all -import Standard.Base.Error.Extensions as Errors +import Standard.Base.Error.Common 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/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/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/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/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/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 7ae6d101e28d..62167c7df5da 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,6 +1,6 @@ from Standard.Base import all - -import Standard.Builtins +import Standard.Base.Runtime.State +import Standard.Base.System ## Creates a new test group, describing 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..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.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.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/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/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/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/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 3704e0e91939..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 @@ -1,26 +1,21 @@ 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 - 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.Numbers 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 +26,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,21 +50,21 @@ 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) + |Cons.rev = acc -> case this of + | Cons h t -> @Tail_Call t.rev (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) val sumListCode = - """from Standard.Builtins import all + """from Standard.Base.Data.List import all | |main = list -> | summator = acc -> list -> case list of @@ -82,7 +77,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 +90,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 +103,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 +116,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 +129,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 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..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.Builtins 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 1ccd1a50c116..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,8 @@ class RecursionFixtures extends DefaultInterpreterRunner { val oversaturatedRecursiveCall = getMain(oversaturatedRecursiveCallTCOCode) val sumStateTCOCode = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers 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,9 @@ class RecursionFixtures extends DefaultInterpreterRunner { val sumTCOWithEval = getMain(sumTCOWithEvalCode) val nestedThunkSumCode = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.Runtime.State + |import Standard.Base.Nothing | |doNTimes = n -> ~block -> | block 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/controlflow/caseexpr/BooleanConstructorBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/BooleanConstructorBranchNode.java index b849d32f6707..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; @@ -19,11 +18,15 @@ 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/controlflow/caseexpr/CaseNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/CaseNode.java index 2b79e93f5db1..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,12 +93,7 @@ public Object doMatch(VirtualFrame frame, Object object) { } CompilerDirectives.transferToInterpreter(); throw new PanicException( - Context.get(this) - .getBuiltins() - .error() - .inexhaustivePatternMatchError() - .newInstance(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/expression/builtin/Any.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java new file mode 100644 index 000000000000..ad28f12ee774 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -0,0 +1,6 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.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 new file mode 100644 index 000000000000..457a9c6492f2 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -0,0 +1,12 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +// 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(name = "Standard.Base.Data.Boolean.Boolean") +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..dd5439e282d2 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -0,0 +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 {} 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..b9398edf89c4 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java @@ -0,0 +1,6 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.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 new file mode 100644 index 000000000000..1189cf7a088f --- /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(name = "Standard.Base.Nothing.Nothing") +public class Nothing 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 new file mode 100644 index 000000000000..1e76617c06db --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Polyglot.java @@ -0,0 +1,6 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType +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 new file mode 100644 index 000000000000..7860b38b8c0f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.bool; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +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 new file mode 100644 index 000000000000..9e6b7d3c54fe --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.bool; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +public class True extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java new file mode 100644 index 000000000000..2c5909e209f0 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/Debug.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.debug; + +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/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..34e56329520d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..648857beb36f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..743932d947da --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..d1a1a2092b00 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..78cad5219e70 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..a3d94f379e74 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..231b5eec4e5b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..5c5b372e9437 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType(params = {"name"}) +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 new file mode 100644 index 000000000000..ec8ad7784a37 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +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 new file mode 100644 index 000000000000..7fa5d73a7c5a --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..0fe5b29d9c9b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..cf93a27632a2 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType(params = {"target"}) +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 new file mode 100644 index 000000000000..6b4ac0462c5b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/Panic.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java new file mode 100644 index 000000000000..afedbf4da69d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..d097110a9583 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..6ec0284ad7e9 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..43c08797f6ed --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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 new file mode 100644 index 000000000000..49c6e118a38d --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType(params = {"arguments"}) +public class UnsupportedArgumentTypes extends Builtin {} 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/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/Function.java new file mode 100644 index 000000000000..56596a32356b --- /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(name = "Standard.Base.Function.Function") +public class Function extends Builtin {} 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/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 { 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/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..07900116447f --- /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/mutable/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java new file mode 100644 index 000000000000..1133dfa4caea --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Array.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.mutable; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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/CopyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/CopyNode.java index e97211f12772..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 @@ -66,6 +66,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/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..8336cd33ad27 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/Ref.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.mutable; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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/BigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java new file mode 100644 index 000000000000..86f820b79ea0 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.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 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..18cbf5359637 --- /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(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 new file mode 100644 index 000000000000..318bbd3fcda3 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.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(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 new file mode 100644 index 000000000000..0c2ee799100a --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Number.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(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/number/SmallInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java new file mode 100644 index 000000000000..b5c255042261 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.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 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 5a83555f408e..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.") +@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 fdeb80647ae5..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.") +@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/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/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..5209451ae159 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.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 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..a6fe2d5b277f --- /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..c502f085bd63 --- /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..fb569d2939bd --- /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..f278f438d9e6 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/resource/ManagedResource.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.resource; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@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/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/node/expression/builtin/state/GetStateNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/state/GetStateNode.java index 22090a0429cb..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 @@ -48,7 +48,7 @@ Object doMultiUncached(SmallMap state, Object _this, Object key) { 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]; } @@ -57,12 +57,12 @@ Object doMultiUncached(SmallMap state, Object _this, Object key) { @Specialization 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 8608bbb0d8bf..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 @@ -54,7 +54,7 @@ Stateful doMultiUncached(SmallMap state, Object _this, Object key, Object new_st 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); } @@ -65,6 +65,6 @@ Stateful doError(Object state, Object _this, Object key, Object new_state) { 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/builtin/system/CreateProcessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/CreateProcessNode.java index 64ad08ae797a..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,10 +114,7 @@ Object doCreate( Text returnOut = Text.create(out.toString()); Text returnErr = Text.create(err.toString()); - return ctx.getBuiltins() - .system() - .getSystemProcessResult() - .newInstance(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 new file mode 100644 index 000000000000..88be18a52123 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -0,0 +1,7 @@ +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/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..27eabf1e0738 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/PrimTextHelper.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.text; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType +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 new file mode 100644 index 000000000000..c83a768f1f22 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/Text.java @@ -0,0 +1,7 @@ +package org.enso.interpreter.node.expression.builtin.text; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.Builtin; + +@BuiltinType(name = "Standard.Base.Data.Text.Text") +public class Text extends Builtin {} 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/node/expression/constant/ConstructorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java index 98622458b716..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 @@ -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.bool().getTrue()) { return true; } - if (constructor == bool.getFalse()) { + if (constructor == builtins.bool().getFalse()) { return false; } if (constructor.getArity() == 0) { 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/Module.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Module.java index e9c04a335e34..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 @@ -469,16 +469,17 @@ 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(); + Builtins builtins = context.getBuiltins(); Function eval = - context - .getBuiltins() - .getScope() - .lookupMethodDefinition(debug, Builtins.MethodNames.Debug.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/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 82d9567eb814..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 @@ -1,54 +1,44 @@ package org.enso.interpreter.runtime.builtin; 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.nio.charset.StandardCharsets; -import java.util.Objects; +import java.util.*; +import java.util.stream.Collectors; + 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.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; -import org.enso.interpreter.node.expression.builtin.error.ThrowPanicMethodGen; -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; -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.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.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.dsl.TypeProcessor; +import org.enso.interpreter.dsl.model.MethodDefinition; +import org.enso.interpreter.node.expression.builtin.*; +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; +import org.enso.interpreter.node.expression.builtin.resource.ManagedResource; +import org.enso.interpreter.node.expression.builtin.text.Text; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.Module; 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.interpreter.runtime.type.TypesFromProxy; import org.enso.pkg.QualifiedName; /** Container class for static predefined atoms, methods, and their containing scope. */ 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. */ @@ -58,29 +48,31 @@ public static class Debug { } } - private final AtomConstructor any; - private final AtomConstructor debug; - private final AtomConstructor projectDescription; - private final AtomConstructor function; - private final AtomConstructor nothing; - private final AtomConstructor panic; - private final AtomConstructor caughtPanic; + private final Map>> builtinMethodNodes; + private final Map builtins; - 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; - private final Number number; + public final Number number; + private final Bool bool; private final Ordering ordering; - private final Polyglot polyglot; - private final Resource resource; private final System system; - private final Text text; private final Special special; + // Builtin types + 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. * @@ -91,115 +83,64 @@ public Builtins(Context context) { module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); scope = module.compileScope(context); - any = new AtomConstructor("Any", scope).initializeFields(); - bool = new Bool(language, scope); - debug = new AtomConstructor("Debug", scope).initializeFields(); - dataflowError = new DataflowError(language, scope); - 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)); - error = new Error(language, scope); - function = new AtomConstructor("Function", scope).initializeFields(); - meta = new Meta(language, scope); - mutable = new Mutable(language, scope); - 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)); - polyglot = new Polyglot(language, scope); - resource = new Resource(language, scope); - system = new System(language, scope); - text = new Text(language, scope); + builtins = new HashMap<>(); + List builtinTypes = readBuiltinTypesMetadata(scope); + builtinMethodNodes = readBuiltinMethodsMetadata(scope); + registerBuiltinMethods(builtinTypes, scope, language); + + error = new Error(this); + 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); + } - 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(); - 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(); - scope.registerConstructor(nothing); - scope.registerConstructor(any); - scope.registerConstructor(function); - - scope.registerConstructor(cons); - scope.registerConstructor(nil); - scope.registerConstructor(io); - scope.registerConstructor(primIo); - scope.registerConstructor(panic); - scope.registerConstructor(caughtPanic); - scope.registerConstructor(state); - scope.registerConstructor(debug); - scope.registerConstructor(projectDescription); - scope.registerConstructor(runtime); - - scope.registerConstructor(java); - scope.registerConstructor(thread); - - 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)); - scope.registerMethod(runtime, "gc", GCMethodGen.makeFunction(language)); - 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(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)); - - scope.registerMethod(debug, MethodNames.Debug.EVAL, DebugEvalMethodGen.makeFunction(language)); - scope.registerMethod(debug, "breakpoint", DebugBreakpointMethodGen.makeFunction(language)); - - 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)); + /** + * 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); + 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)); + }); + } + } } /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ @@ -210,16 +151,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(""); } /** @@ -240,13 +172,169 @@ 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; + 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 > 4) { + throw new CompilerError("Invalid builtin metadata in: " + line); + } + + AtomConstructor builtin; + builtin = new AtomConstructor(builtinMeta[0], scope, true); + + if (builtinMeta.length < 3 || builtinMeta[2].isEmpty()) { + 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: : + * + * @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; + 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(); + } + 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; + } + + /** + * 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()); + 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(); + } + } + + 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 builtins.get(name); + } + /** * Returns the {@code Nothing} atom constructor. * * @return the {@code Nothing} atom constructor */ public AtomConstructor nothing() { - return nothing; + return nothing.constructor(); } /** @@ -254,8 +342,8 @@ public AtomConstructor nothing() { * * @return the {@code Text} part of builtins. */ - public Text text() { - return text; + public AtomConstructor text() { + return text.constructor(); } /** @@ -264,7 +352,7 @@ public Text text() { * @return the {@code Function} atom constructor */ public AtomConstructor function() { - return function; + return function.constructor(); } /** @@ -276,11 +364,16 @@ public Number number() { return number; } - /** @return the Boolean part of builtins. */ + /** @return the container for boolean constructors. */ public Bool bool() { return bool; } + /** @return the ManagedResource constructor. */ + public AtomConstructor managedResource() { + return managedResource.constructor(); + } + /** @return the builtin Error types container. */ public Error error() { return error; @@ -292,21 +385,22 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - return any; + return any.constructor(); } /** - * Returns the {@code Debug} atom constructor. + * 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() { - return debug; + return debug.constructor(); } - /** @return the {@code Enso_Project} atom constructor */ + /** @return the {@code Project_Description} atom constructor */ public AtomConstructor getProjectDescription() { - return projectDescription; + return projectDescription.constructor(); } /** @return the {@code System} atom constructor. */ @@ -314,19 +408,29 @@ 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 array.constructor(); + } + + /** @return the Ref constructor. */ + public AtomConstructor ref() { + return ref.constructor(); } /** @return the container for polyglot-related builtins. */ - public Polyglot polyglot() { - return polyglot; + public AtomConstructor polyglot() { + return polyglot.constructor(); } /** @return the {@code Caught_Panic} atom constructor */ public AtomConstructor caughtPanic() { - return caughtPanic; + return this.error.caughtPanic(); + } + + /** @return the {@code Panic} atom constructor */ + public AtomConstructor panic() { + return this.error.panic(); } /** @return the container for ordering-related builtins */ @@ -335,8 +439,8 @@ public Ordering ordering() { } /** @return the container for the dataflow error-related builtins */ - public DataflowError dataflowError() { - return dataflowError; + public AtomConstructor dataflowError() { + return dataflowError.constructor(); } public Special special() { @@ -359,40 +463,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 mutable.array().newInstance(); - case Constants.BOOLEAN: - return bool.getBool().newInstance(); - case Constants.DECIMAL: - return number.getDecimal().newInstance(); - case Constants.ERROR: - return dataflowError.constructor().newInstance(); - case Constants.FUNCTION: - return function.newInstance(); - case Constants.INTEGER: - return number.getInteger().newInstance(); - case Constants.MANAGED_RESOURCE: - return resource.getManagedResource().newInstance(); - case Constants.NOTHING: - return nothing.newInstance(); - case Constants.NUMBER: - return number.getNumber().newInstance(); - case Constants.PANIC: - return panic.newInstance(); - case Constants.REF: - return mutable.ref().newInstance(); - case Constants.TEXT: - return text.getText().newInstance(); - default: - return null; - } + return TypesFromProxy.fromTypeSystem(this, typeName); } } 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 b72fc979801e..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 @@ -1,225 +1,97 @@ package org.enso.interpreter.runtime.builtin; -import org.enso.interpreter.Language; -import org.enso.interpreter.node.expression.builtin.error.displaytext.*; +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; 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; + +import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; /** 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 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; + + @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. - */ - 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)); + /** Creates builders for error Atom Constructors. */ + public Error(Builtins builtins) { + syntaxError = new BuiltinAtomConstructor(builtins, SyntaxError.class); + typeError = new BuiltinAtomConstructor(builtins, TypeError.class); + compileError = new BuiltinAtomConstructor(builtins, CompileError.class); 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)); - + 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 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)); + 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); + } - 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 Atom makeSyntaxError(Object message) { + return syntaxError.newInstance(message); } - /** @return the builtin {@code Syntax_Error} atom constructor. */ - public AtomConstructor syntaxError() { - return syntaxError; + public Atom makeCompileError(Object message) { + return compileError.newInstance(message); } - /** @return the builtin {@code Type_Error} atom constructor. */ - public AtomConstructor typeError() { - return typeError; + public Atom makeInexhaustivePatternMatchError(Object message) { + return inexhaustivePatternMatchError.newInstance(message); } - /** @return the builtin {@code Compile_Error} atom constructor. */ - public AtomConstructor compileError() { - return compileError; + public Atom makeUninitializedStateError(Object key) { + return uninitializedState.newInstance(key); } - /** @return the builtin {@code Inexhaustive_Pattern_Match_Error} atom constructor. */ - public AtomConstructor inexhaustivePatternMatchError() { - return inexhaustivePatternMatchError; + public Atom makeModuleNotInPackageError() { + return moduleNotInPackageError.newInstance(); } - /** @return the builtin {@code Uninitialized_State} atom constructor. */ - public AtomConstructor uninitializedState() { - return uninitializedState; + public AtomConstructor panic() { + return panic.constructor(); } - /** @return the builtin {@code Module_Not_In_Package_Error} atom constructor. */ - public AtomConstructor moduleNotInPackageError() { - return moduleNotInPackageError; + public AtomConstructor caughtPanic() { + return caughtPanic.constructor(); } /** @@ -270,17 +142,25 @@ 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) { + 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) { + transferToInterpreterAndInvalidate(); + arithmeticErrorShiftTooBig = makeArithmeticError(shiftTooBigMessage); + } return arithmeticErrorShiftTooBig; } /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { + if (arithmeticErrorDivideByZero == null) { + transferToInterpreterAndInvalidate(); + arithmeticErrorDivideByZero = makeArithmeticError(divideByZeroMessage); + } return arithmeticErrorDivideByZero; } 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 44bb8780cec6..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java +++ /dev/null @@ -1,60 +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/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 3e055e01e228..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java +++ /dev/null @@ -1,51 +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; - - /** - * 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(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)); - - 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. */ - public AtomConstructor array() { - return array; - } - - /** @return the Ref constructor. */ - public AtomConstructor ref() { - return ref; - } -} 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 09c940bcce0e..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 @@ -1,409 +1,56 @@ 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; - - /** - * Creates and registers number builtins. - * - * @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, - "%", - org.enso.interpreter.node.expression.builtin.number.decimal.ModMethodGen.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)); + private final BuiltinAtomConstructor smallInteger; + private final BuiltinAtomConstructor bigInteger; + private final BuiltinAtomConstructor integer; + private final BuiltinAtomConstructor number; + private final BuiltinAtomConstructor decimal; + + /** Creates builders for number Atom Constructors. */ + public Number(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() { - return smallInteger; + return smallInteger.constructor(); } /** @return the Big_Integer atom constructor. */ public AtomConstructor getBigInteger() { - return bigInteger; + return bigInteger.constructor(); } /** @return the Integer atom constructor */ public AtomConstructor getInteger() { - return integer; + return integer.constructor(); } /** @return the Number atom constructor */ public AtomConstructor getNumber() { - return number; + return number.constructor(); } /** @return the Decimal atom constructor */ public AtomConstructor getDecimal() { - 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 53079322dd80..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 @@ -1,26 +1,30 @@ 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); + private final BuiltinAtomConstructor ordering; + private final BuiltinAtomConstructor less; + private final BuiltinAtomConstructor equal; + private final BuiltinAtomConstructor greater; + + public Ordering(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); } /** @@ -41,36 +45,36 @@ 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() { - return ordering; + return ordering.constructor(); } /** @return the Less constructor */ public AtomConstructor less() { - return less; + return less.constructor(); } /** @return the Equal constructor */ public AtomConstructor equal() { - return equal; + return equal.constructor(); } /** @return the Greater constructor */ public AtomConstructor greater() { - return greater; + return greater.constructor(); } } 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/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..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 @@ -1,50 +1,25 @@ 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 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. - */ - 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; + /** Create builders for all {@code System} atom constructors. */ + public System(Builtins builtins) { + systemProcessResult = new BuiltinAtomConstructor(builtins, SystemProcessResult.class); } /** @return the atom constructor for {@code Process_Result}. */ - public AtomConstructor getSystemProcessResult() { - return systemProcessResult; + public Atom makeSystemResult(Object exitCode, Object stdout, Object stderr) { + return systemProcessResult.newInstance(exitCode, stdout, stderr); } } 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/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/java/org/enso/interpreter/runtime/callable/atom/Atom.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/Atom.java index ae097d0aec05..cb1ff486d06d 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 @@ -28,7 +28,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 e7bed0c7d65d..d62feefba716 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; @@ -29,13 +30,16 @@ 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) public final 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,8 +52,47 @@ public final class AtomConstructor implements TruffleObject { * @param definitionScope the scope in which this constructor was defined */ 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; + this.builtin = builtin; + } + + public boolean isInitialized() { + return constructorFunction != null; + } + + public boolean isBuiltin() { + return builtin; + } + + 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. + CompilerAsserts.neverPartOfCompilation(); + 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/data/Array.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Array.java index 4f96e8d45dc2..3a55bf90ff04 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 @@ -130,8 +130,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor( - context.getBuiltins().mutable().array(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().array(), context.getBuiltins().any()); } static Context getContext() { @@ -177,7 +176,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/data/text/Text.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java index 8332dcc3ded5..7740cd1fe641 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() { @@ -242,7 +242,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/error/DataflowError.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/DataflowError.java index 8e03a5b84822..66f2e87ce0c1 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/library/dispatch/DefaultBooleanExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultBooleanExports.java index 37ab813cce50..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 @@ -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; @@ -31,22 +31,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.bool().getFalse()) != null) { return null; } - if (symbol.resolveFor(bool.getTrue()) != null) { + if (symbol.resolveFor(builtins.bool().getTrue()) != null) { return null; } - return symbol.resolveFor(bool.getBool(), context.getBuiltins().any()); + return symbol.resolveFor(builtins.bool().getBool(), 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.bool().getTrue() : builtins.bool().getFalse(); + return symbol.resolveFor(cons, builtins.bool().getBool(), context.getBuiltins().any()); } static Context getContext() { @@ -129,23 +129,24 @@ static class GetConversionFunction { 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.bool().getFalse()) != null) { return null; } - if (conversion.resolveFor(target, bool.getTrue()) != null) { + if (conversion.resolveFor(target, builtins.bool().getTrue()) != null) { return null; } - return conversion.resolveFor(target, bool.getBool(), context.getBuiltins().any()); + return conversion.resolveFor(target, builtins.bool().getBool(), 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.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/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index b168625bdf53..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 @@ -115,6 +115,8 @@ public void registerMethod(AtomConstructor atom, String method, Function functio Map methodMap = ensureMethodMapFor(atom); if (methodMap.containsKey(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); @@ -128,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<>()); } @@ -196,10 +196,12 @@ public Function lookupMethodDefinition(AtomConstructor atom, String name) { if (definedWithAtom != null) { return definedWithAtom; } + Function definedHere = getMethodMapFor(atom).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 731d9ad32f57..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,22 +1,10 @@ package org.enso.interpreter.runtime.type; -/** Types defined in the Standard.Builtins module. */ 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 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 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"; + // 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 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 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/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..43353c792fba --- /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().getBool().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/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 deleted file mode 100644 index 4fd145412268..000000000000 --- a/engine/runtime/src/main/resources/Builtins.enso +++ /dev/null @@ -1,2159 +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. - -## 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 - - ## 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" - -# 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 - - ## 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 - - ## 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 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. - - name: The name of the argument whose type is mismatched. -@Builtin_Type -type Type_Error expected actual name - -## 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 - - ## 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 - -## 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: - - 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 - - ## 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 - - ## 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" - -## 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" - -## 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 - - ## 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) 7 - 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 - 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./" - - ## 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. - - > Example - Computing the remainder when dividing 3.5 by 2. - - 3.5 % 2 == 1.5 - - > Example - Computing the fractional part of a number. - - 10.5 % 1.0 == 0.5 - % : Number -> Number ! Arithmetic_Error - % 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" - -## 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 - -## 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 - - ## 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 - -## 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 - -## 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 - - ## 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/main/scala/org/enso/compiler/Compiler.scala b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala index 9e828ad962b8..ac102b1babc6 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 8c4d4cf67685..66c3dbc76d59 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 @@ -18,6 +18,7 @@ import org.enso.compiler.pass.analyse.{ } import org.enso.compiler.pass.optimise.ApplicationSaturation import org.enso.compiler.pass.resolve.{ + ExpressionAnnotations, MethodDefinitions, Patterns, UppercaseNames @@ -78,6 +79,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 @@ -233,13 +235,14 @@ 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 @@ -289,6 +292,31 @@ 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 + .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) + ) + .map(_.filterNot(_ => cons.isBuiltin)) case fn: IR.Function => val bodyBuilder = new expressionProcessor.BuildFunctionBody(fn.arguments, fn.body) @@ -303,17 +331,30 @@ class IrToTruffle( ) val callTarget = Truffle.getRuntime.createCallTarget(rootNode) val arguments = bodyBuilder.args() - new RuntimeFunction( - callTarget, - null, - new FunctionSchema(arguments: _*) + Right( + Some( + new RuntimeFunction( + callTarget, + null, + new FunctionSchema(arguments: _*) + ) + ) ) case _ => - throw 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." + ) ) } - moduleScope.registerMethod(cons, methodDef.methodName.name, function) + 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 + } } }) @@ -381,6 +422,19 @@ class IrToTruffle( // === 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 @@ -683,8 +737,7 @@ class IrToTruffle( ErrorNode.build( context.getBuiltins .error() - .syntaxError() - .newInstance( + .makeSyntaxError( Text.create( "Type operators are not currently supported at runtime." ) @@ -729,8 +782,7 @@ class IrToTruffle( val error = context.getBuiltins .error() - .compileError() - .newInstance(Text.create(message)) + .makeCompileError(Text.create(message)) setLocation(ErrorNode.build(error), caseExpr.location) } @@ -826,24 +878,28 @@ class IrToTruffle( ) runtimeConsOpt.map { atomCons => - val any = context.getBuiltins.any - val array = context.getBuiltins.mutable.array - val bool = context.getBuiltins.bool - val number = context.getBuiltins.number - val polyglot = context.getBuiltins.polyglot.getPolyglot - val text = context.getBuiltins.text + val any = context.getBuiltins.any + val array = context.getBuiltins.array + 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 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 == builtinBool) { BooleanConstructorBranchNode.build( - bool, + builtinBool, + builtinTrue, + 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) { @@ -854,9 +910,9 @@ class IrToTruffle( } else if (atomCons == number.getNumber) { NumberBranchNode.build(number, branchCodeNode.getCallTarget) } else if (atomCons == array) { - ArrayBranchNode.build(array, branchCodeNode.getCallTarget) + ArrayBranchNode.build(atomCons, branchCodeNode.getCallTarget) } else if (atomCons == polyglot) { - PolyglotBranchNode.build(polyglot, branchCodeNode.getCallTarget) + PolyglotBranchNode.build(atomCons, branchCodeNode.getCallTarget) } else if (atomCons == any) { CatchAllBranchNode.build(branchCodeNode.getCallTarget) } else { @@ -1122,53 +1178,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." @@ -1374,8 +1420,7 @@ class IrToTruffle( ErrorNode.build( context.getBuiltins .error() - .syntaxError() - .newInstance( + .makeSyntaxError( Text.create( "Typeset literals are not yet supported at runtime." ) 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 b246761acd59..1391ba780fa1 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,14 +1,16 @@ 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 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. * @@ -22,8 +24,17 @@ class RuntimeStubsGenerator() { "Non-parsed module used in stubs generator" ) localBindings.constructors.foreach { tp => - val constructor = new AtomConstructor(tp.name, scope) - scope.registerConstructor(constructor) + 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 { + val constructor = new AtomConstructor(tp.name, scope) + scope.registerConstructor(constructor) + } } } } 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 6319ab319853..fe216b2a9b48 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 @@ -692,6 +691,6 @@ object SuggestionBuilder { } - val Any: String = Constants.ANY + val Any: String = "Standard.Base.Any.Any" } 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 c4468797dd43..3519a4344775 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 @@ -6453,6 +6453,17 @@ 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/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index 93cb924f2e96..3de9dedf2d3a 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 @@ -735,8 +735,14 @@ object BindingsMap { * @param name the name of the constructor. * @param arity the number of fields in the constructor. * @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) + case class Cons( + name: String, + arity: Int, + allFieldsDefaulted: Boolean, + builtinType: Boolean = false + ) /** A representation of a sum type * 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 f8f4a280b857..1a995844fc48 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 @@ -11,7 +11,11 @@ import org.enso.compiler.pass.desugar.{ FunctionBinding, GenerateMethodBodies } -import org.enso.compiler.pass.resolve.{MethodDefinitions, Patterns} +import org.enso.compiler.pass.resolve.{ + MethodDefinitions, + ModuleAnnotations, + Patterns +} import scala.annotation.unused @@ -53,10 +57,15 @@ case object BindingAnalysis extends IRPass { val definedConstructors = ir.bindings.collect { case cons: IR.Module.Scope.Definition.Atom => + // 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, - cons.arguments.forall(_.defaultValue.isDefined) + cons.arguments.forall(_.defaultValue.isDefined), + isBuiltinType ) } val importedPolyglot = ir.imports.collect { 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 bd0d6a91f641..b18e3c095819 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,15 @@ 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 => { + 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/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/UnusedBindings.scala index 986d2e56f138..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 @@ -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 @@ -135,9 +135,26 @@ 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( @@ -259,4 +276,18 @@ 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/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/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/InstrumentTestContext.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala new file mode 100644 index 000000000000..b49cd1d89384 --- /dev/null +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/InstrumentTestContext.scala @@ -0,0 +1,48 @@ +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 receive: Option[Api.Response] = { + Option(messageQueue.poll(10, TimeUnit.SECONDS)) + } + + 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] = { + receiveN(n + 1, 60).filter(excludeLibraryLoadingPayload) + } + + private def excludeLibraryLoadingPayload(response: Api.Response): Boolean = + response match { + case Api.Response(None, Api.LibraryLoaded(_, _, _, _)) => + false + case _ => + true + } + +} + +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/ReplTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 983d61537b55..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 @@ -23,7 +23,7 @@ class ReplTest "initialize properly" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = Debug.breakpoint |""".stripMargin @@ -34,7 +34,7 @@ class ReplTest "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 @@ -54,7 +54,7 @@ class ReplTest "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 @@ -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 | @@ -116,7 +116,7 @@ class ReplTest "be able to define its local variables" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -134,7 +134,7 @@ class ReplTest "not overwrite bindings" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -151,7 +151,9 @@ class ReplTest "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.Base.Data.Numbers import Number | |run = | State.put Number 10 @@ -171,7 +173,7 @@ class ReplTest "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 @@ -197,7 +199,7 @@ class ReplTest "be able to list bindings it has created" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 10 @@ -224,7 +226,7 @@ class ReplTest "allow to be nested" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | 10 * Debug.breakpoint + 1 @@ -247,7 +249,7 @@ class ReplTest "behave well when nested" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | x = 1 @@ -274,7 +276,7 @@ class ReplTest "handle errors gracefully" in { val code = """ - |from Standard.Builtins import all + |import Standard.Base.Runtime.Debug | |main = | Debug.breakpoint @@ -294,7 +296,8 @@ class ReplTest "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 = | Debug.breakpoint @@ -320,7 +323,7 @@ class ReplTest "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/RuntimeErrorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index 5092e8b856c6..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 @@ -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._ @@ -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)) @@ -64,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, "true") + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( @@ -97,18 +97,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(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() @@ -174,7 +162,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( @@ -258,7 +246,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( @@ -292,13 +280,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 +325,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -363,12 +351,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 @@ -404,7 +392,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( @@ -432,8 +420,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") @@ -444,12 +432,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 +475,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( @@ -506,8 +494,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") @@ -518,12 +506,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 +549,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -573,7 +561,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)") @@ -592,9 +580,9 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("1234567890123456788") @@ -613,7 +601,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( TestMessages.error( contextId, xId, @@ -644,9 +632,9 @@ class RuntimeErrorsTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), + context.receiveN(3) should contain theSameElementsAs Seq( + TestMessages.update(contextId, xId, ConstantsGen.INTEGER), + TestMessages.update(contextId, yId, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("499999999999") @@ -657,12 +645,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 +689,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -713,7 +701,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)") @@ -732,7 +720,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)") @@ -743,13 +731,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 +779,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -804,7 +792,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)") @@ -823,7 +811,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)") @@ -834,12 +822,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 | @@ -877,7 +865,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -921,10 +909,11 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + + context.receiveNIgnoreStdLib(4) should contain theSameElementsAs Seq( + 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") @@ -935,12 +924,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 @@ -976,7 +965,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( @@ -1033,10 +1022,10 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( - TestMessages.update(contextId, xId, Constants.INTEGER), - TestMessages.update(contextId, yId, Constants.INTEGER), - TestMessages.update(contextId, mainResId, Constants.NOTHING), + context.receiveN(4) should contain theSameElementsAs Seq( + 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") @@ -1048,12 +1037,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 +1081,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1136,7 +1125,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( TestMessages.panic( contextId, xId, @@ -1171,12 +1160,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 @@ -1215,7 +1204,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1260,15 +1249,15 @@ class RuntimeErrorsTest ) ) ) - context.receive(4) should contain theSameElementsAs Seq( + context.receiveN(4) should contain theSameElementsAs Seq( 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") @@ -1279,12 +1268,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(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 = | Error.throw 9 @@ -1323,7 +1313,7 @@ class RuntimeErrorsTest ) ) ) - context.receive(5) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(5) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1339,7 +1329,7 @@ class RuntimeErrorsTest TestMessages.update( contextId, mainResId, - Constants.NOTHING + ConstantsGen.NOTHING ), context.executionComplete(contextId) ) @@ -1352,21 +1342,21 @@ 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" ) ) ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveN(3) should contain theSameElementsAs Seq( 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") @@ -1381,8 +1371,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 = @@ -1418,7 +1408,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( @@ -1461,15 +1451,15 @@ 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( - TestMessages.update(contextId, x1Id, Constants.NOTHING), - TestMessages.update(contextId, mainRes1Id, Constants.NOTHING), + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( + 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 f95be531677f..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 @@ -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`.{Constants, ConstantsGen} import org.enso.interpreter.test.Metadata import org.enso.pkg.{Package, PackageManager} import org.enso.polyglot._ @@ -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")) @@ -58,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, "true") + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( @@ -91,18 +90,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() @@ -159,9 +146,9 @@ 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), + TestMessages.update(contextId, mainBody, ConstantsGen.INTEGER), context.executionComplete(contextId) ) } @@ -172,13 +159,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) @@ -208,9 +193,9 @@ 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), + TestMessages.update(contextId, mainBody, ConstantsGen.TEXT), context.executionComplete(contextId) ) } @@ -261,7 +246,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 +264,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 @@ -323,13 +308,13 @@ 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), - 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) ) } @@ -340,14 +325,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 @@ -383,13 +368,13 @@ 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), - 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) ) } @@ -400,16 +385,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,11 +425,11 @@ 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), - 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) ) } @@ -458,14 +441,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,11 +480,11 @@ 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), - 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) ) } @@ -515,14 +496,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 = @@ -558,17 +538,17 @@ 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.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) ) } @@ -580,14 +560,14 @@ class RuntimeInstrumentTest val metadata = new Metadata // 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) + metadata.addItem(42, 5) + 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 @@ -623,12 +603,12 @@ 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), - 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) ) } @@ -639,16 +619,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 @@ -683,11 +663,11 @@ 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), - 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) ) } @@ -698,14 +678,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 @@ -740,11 +720,11 @@ 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), - 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") @@ -757,17 +737,15 @@ 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 - | - |main = + """main = | x = | f x = x + 1 | f 42 @@ -802,7 +780,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), @@ -817,19 +795,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 @@ -864,7 +840,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), @@ -879,17 +855,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 @@ -924,7 +898,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), @@ -939,24 +913,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 = @@ -996,11 +969,11 @@ 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), - 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 d7d934d13da0..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 @@ -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} @@ -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)) @@ -62,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, "true") + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( @@ -98,18 +98,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(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() @@ -125,16 +113,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(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( """ - |from Standard.Builtins import all + |from Standard.Base.Data.Numbers import Number | |main = | x = 6 @@ -158,7 +146,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idMainX, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -175,11 +163,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" ) ), @@ -198,7 +186,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -215,7 +203,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idFooY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -232,7 +220,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( Main.idFooZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -247,12 +235,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!" @@ -279,7 +267,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( idMainY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", @@ -302,7 +290,7 @@ class RuntimeServerTest Set( Api.ExpressionUpdate( idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), Some( Api.MethodPointer( "Enso_Test.Test.Main", @@ -376,7 +364,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -389,7 +377,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), @@ -414,7 +402,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) @@ -439,11 +427,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 | @@ -479,15 +467,15 @@ 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, 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") @@ -499,7 +487,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) ) @@ -512,16 +500,16 @@ 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(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 Enso_Test.Test.A | |type Quux @@ -544,8 +532,7 @@ class RuntimeServerTest val mainFile = context.writeMain(contents) val aCode = - """from Standard.Builtins import all - | + """ |type A | type A un_a | @@ -583,12 +570,12 @@ 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, idMainX, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer( "Enso_Test.Test.Main", "Enso_Test.Test.Main.Quux", @@ -598,24 +585,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") @@ -627,13 +614,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 @@ -667,15 +652,15 @@ 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, 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) ) } @@ -686,11 +671,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 | @@ -726,15 +711,15 @@ 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, 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") @@ -746,11 +731,13 @@ 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(113, 41) + val idMainBar = metadata.addItem(145, 8) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.IO + |import Standard.Base.Runtime.State | |main = IO.println (State.run Number 42 this.bar) | @@ -785,15 +772,15 @@ 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, 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") @@ -805,11 +792,13 @@ 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(113, 40) + val idMainBar = metadata.addItem(144, 8) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.IO + |import Standard.Base.Runtime.State | |main = IO.println (State.run Number 0 this.bar) | @@ -846,15 +835,15 @@ 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, 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") @@ -866,13 +855,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 @@ -907,15 +894,15 @@ 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, 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) ) } @@ -927,16 +914,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 @@ -975,16 +962,16 @@ 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, 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") @@ -996,10 +983,10 @@ class RuntimeServerTest Api.PushContextRequest(contextId, Api.StackItem.LocalCall(mainFoo)) ) ) - context.receive(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), + TestMessages.update(contextId, fooX, ConstantsGen.INTEGER), + TestMessages.update(contextId, fooRes, ConstantsGen.INTEGER), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("4") @@ -1018,20 +1005,20 @@ 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.receiveN(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PopContextResponse(contextId)), TestMessages .update( contextId, mainFoo, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer("Enso_Test.Test.Main", "Enso_Test.Test.Main", "foo") ), context.executionComplete(contextId) @@ -1043,7 +1030,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(54, 47) val contents = context.Main.code val mainFile = context.writeMain(contents) @@ -1073,12 +1060,12 @@ class RuntimeServerTest ) ) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1087,7 +1074,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), @@ -1096,7 +1083,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) @@ -1104,7 +1091,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)) ) } @@ -1115,11 +1102,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 @@ -1154,11 +1141,11 @@ 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), - 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") @@ -1177,8 +1164,8 @@ class RuntimeServerTest ) ) ) - context.receive(2) should contain theSameElementsAs Seq( - TestMessages.update(contextId, idResult, Constants.TEXT), + context.receiveN(2) should contain theSameElementsAs Seq( + TestMessages.update(contextId, idResult, ConstantsGen.TEXT), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("Hi") @@ -1190,19 +1177,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(77, 35) + val idMainA = metadata.addItem(86, 8) + val idMainP = metadata.addItem(99, 12) // pie id - metadata.addItem(75 + 8, 1) + metadata.addItem(119, 1) // uwu id - metadata.addItem(83 + 8, 1) + metadata.addItem(127, 1) // hie id - metadata.addItem(91 + 8, 6) + metadata.addItem(135, 6) // Number.x id - metadata.addItem(111 + 8, 1) + metadata.addItem(155, 1) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.IO | |main = | a = 123 + 21 @@ -1242,11 +1230,11 @@ 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), - 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") @@ -1258,19 +1246,19 @@ 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.receiveN(2) should contain theSameElementsAs Seq( TestMessages.update( contextId, idMainA, - Constants.INTEGER, - Api.MethodPointer(moduleName, Constants.NUMBER, "x") + ConstantsGen.INTEGER, + Api.MethodPointer(moduleName, ConstantsGen.NUMBER, "x") ), context.executionComplete(contextId) ) @@ -1283,14 +1271,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/ @@ -1300,18 +1288,18 @@ 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, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "pie") ), context.executionComplete(contextId) @@ -1325,18 +1313,18 @@ 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, - Constants.INTEGER, + ConstantsGen.INTEGER, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "uwu") ), context.executionComplete(contextId) @@ -1350,18 +1338,18 @@ 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, - Constants.TEXT, + ConstantsGen.TEXT, Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "hie") ), context.executionComplete(contextId) @@ -1375,15 +1363,15 @@ 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( - TestMessages.update(contextId, idMainA, Constants.TEXT), + context.receiveN(2) should contain theSameElementsAs Seq( + TestMessages.update(contextId, idMainA, ConstantsGen.TEXT), context.executionComplete(contextId) ) context.consumeOut shouldEqual List("Hello!") @@ -1395,20 +1383,26 @@ 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(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.Builtins import all + """from Standard.Base.Data.Numbers import Number + |from Standard.Base.Data.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 + |Text.Text.overloaded arg = arg + 1 |Number.overloaded arg = arg + 2 |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) @@ -1440,26 +1434,26 @@ class RuntimeServerTest ) ) ) - context.receive(6) 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(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) ) @@ -1474,33 +1468,33 @@ 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, 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) ) @@ -1515,33 +1509,33 @@ 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, 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) ) @@ -1556,33 +1550,33 @@ 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, 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) ) @@ -1594,11 +1588,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 @@ -1633,10 +1627,10 @@ 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), + TestMessages.update(contextId, xId, ConstantsGen.FUNCTION), + TestMessages.update(contextId, mainRes, ConstantsGen.NOTHING), context.executionComplete(contextId) ) } @@ -1652,7 +1646,7 @@ class RuntimeServerTest 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 @@ -1680,7 +1674,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) ) @@ -1745,9 +1739,9 @@ 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), + TestMessages.update(contextId, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1774,7 +1768,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(54, 47) val mainFile = context.writeMain(context.Main.code) @@ -1799,12 +1793,12 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1813,7 +1807,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), @@ -1822,7 +1816,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) @@ -1830,7 +1824,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)) ) @@ -1853,7 +1847,8 @@ class RuntimeServerTest ) val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.IO | |main = IO.println "I'm a file!" |""".stripMargin @@ -1881,7 +1876,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) ) @@ -1889,7 +1884,8 @@ class RuntimeServerTest /* Modify the file: - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.IO | |Number.lucky = 42 | @@ -1902,18 +1898,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!") @@ -1952,7 +1948,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -1964,7 +1960,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) ) @@ -1998,7 +1994,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -2016,7 +2012,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) ) @@ -2050,7 +2046,7 @@ class RuntimeServerTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -2070,7 +2066,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) ) @@ -2108,7 +2104,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( @@ -2156,7 +2152,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2207,7 +2203,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionFailed( @@ -2261,7 +2257,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( @@ -2329,7 +2325,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( @@ -2405,7 +2401,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( @@ -2450,7 +2446,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Number | |main = Number.pi |""".stripMargin.linesIterator.mkString("\n") @@ -2483,7 +2479,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2552,7 +2548,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( @@ -2579,9 +2575,8 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = this.foo + """main = + | this.foo | |foo = | x = this.bar @@ -2622,7 +2617,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( @@ -2639,7 +2634,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 ), @@ -2647,7 +2642,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 ), @@ -2655,7 +2650,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 ), @@ -2663,7 +2658,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 ) @@ -2683,9 +2678,8 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = x = 1 + """main = + | x = 1 |""".stripMargin.linesIterator.mkString("\n") val contents = metadata.appendToCode(code) val mainFile = context.writeMain(contents) @@ -2716,7 +2710,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( @@ -2725,7 +2719,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 ) ) @@ -2742,9 +2736,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") @@ -2777,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( @@ -2786,7 +2778,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))) ) ) ) @@ -2802,9 +2794,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all - | - |main = + """main = | x = 1 | x = 2 |""".stripMargin.linesIterator.mkString("\n") @@ -2837,7 +2827,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( @@ -2846,12 +2836,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))) ) ) ) @@ -2866,10 +2856,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 +2892,7 @@ class RuntimeServerTest ) ) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), Api.Response( Api.ExecutionUpdate( @@ -2918,7 +2909,8 @@ class RuntimeServerTest context.executionComplete(contextId) ) context.consumeOut shouldEqual List( - "(Error: (Syntax_Error 'Unrecognized token.'))" + "(Error: (Syntax_Error 'Unrecognized token.'))", + "(Syntax_Error 'Unrecognized token.')" ) } @@ -2929,7 +2921,8 @@ 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 = | x = Panic.catch_primitive () .convert_to_dataflow_error @@ -2965,7 +2958,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( @@ -2974,7 +2967,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))) ) ) ) @@ -2989,7 +2982,7 @@ class RuntimeServerTest val metadata = new Metadata val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |foo = 1 |foo = 2 @@ -3025,7 +3018,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( @@ -3069,7 +3062,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), @@ -3081,7 +3074,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) ) @@ -3126,7 +3119,7 @@ class RuntimeServerTest ) ) ) - context.receive(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), @@ -3139,7 +3132,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")) ) @@ -3147,7 +3140,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) ) @@ -3162,13 +3155,13 @@ 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, 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/RuntimeStdlibTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeStdlibTest.scala index 61b979c28586..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, "true") + .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 4ae0691f29e0..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 @@ -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 @@ -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)) @@ -50,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, "true") + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option(RuntimeServerInfo.ENABLE_OPTION, "true") .option(RuntimeOptions.INTERACTIVE_MODE, "true") .option( @@ -76,18 +76,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(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() @@ -112,7 +100,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") @@ -145,7 +133,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( @@ -184,7 +172,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -215,12 +203,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 + """from Standard.Base import all | |main = | x = 42 @@ -248,7 +236,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -262,7 +250,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(4, 16) @@ -300,12 +288,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 + """from Standard.Base import all | |main = | x = 42 @@ -334,7 +322,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -348,7 +336,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(4, 16) @@ -371,7 +359,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "y", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(5, 18) @@ -405,12 +393,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 + """from Standard.Base import all | |main = | x = 42 @@ -440,7 +428,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -454,7 +442,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(5, 18) @@ -477,14 +465,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), @@ -519,12 +507,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 + """from Standard.Base import all | |foo x = x * 10 | @@ -556,7 +544,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -570,7 +558,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(6, 18) @@ -593,7 +581,7 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "y", - Constants.NUMBER, + ConstantsGen.NUMBER, Suggestion.Scope( Suggestion.Position(2, 6), Suggestion.Position(6, 18) @@ -628,10 +616,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 @@ -662,12 +650,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 + """from Standard.Base import all | |foo a b = a * b | @@ -698,10 +686,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 @@ -715,7 +703,7 @@ class RuntimeSuggestionUpdatesTest Api.SuggestionArgumentAction.Add( 2, Suggestion - .Argument("b", Constants.ANY, false, false, None) + .Argument("b", ConstantsGen.ANY, false, false, None) ) ) ), @@ -740,8 +728,13 @@ 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.Builtins import all + """from Standard.Base.Data.Numbers import Number + |import Standard.Base.Data.Text + |import Standard.Base.Nothing | |main = | x = 15.overloaded 1 @@ -749,7 +742,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) @@ -781,7 +774,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( @@ -820,7 +813,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -834,10 +827,10 @@ class RuntimeSuggestionUpdatesTest None, moduleName, "x", - Constants.ANY, + ConstantsGen.ANY, Suggestion.Scope( - Suggestion.Position(2, 6), - Suggestion.Position(7, 0) + Suggestion.Position(4, 6), + Suggestion.Position(9, 0) ) ), Api.SuggestionAction.Add() @@ -855,16 +848,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 @@ -882,16 +875,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 @@ -914,7 +907,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 @@ -922,7 +915,7 @@ class RuntimeSuggestionUpdatesTest |main = IO.println "Hello World!" |""".stripMargin.linesIterator.mkString("\n") val aCode = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import Integer | |type MyType | type MkA a @@ -967,7 +960,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( @@ -993,7 +986,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, @@ -1021,7 +1014,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.A.MkA", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -1039,14 +1032,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 @@ -1071,7 +1064,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.A", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -1132,7 +1125,7 @@ class RuntimeSuggestionUpdatesTest ) ), "Enso_Test.Test.Main", - Constants.ANY, + ConstantsGen.ANY, None, None, None @@ -1163,12 +1156,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 | |import Enso_Test.Test.A |from Enso_Test.Test.A export all hiding hello @@ -1207,12 +1200,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/instrument/RuntimeVisualisationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/instrument/RuntimeVisualisationsTest.scala index 1c45762d58fe..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 @@ -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} @@ -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)) @@ -65,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, "true") + .option( + RuntimeOptions.DISABLE_IR_CACHES, + InstrumentTestContext.DISABLE_IR_CACHE + ) .option( RuntimeOptions.LANGUAGE_HOME_OVERRIDE, Paths.get("../../distribution/component").toFile.getAbsolutePath @@ -97,23 +97,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() @@ -129,16 +112,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(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( """ - |from Standard.Builtins import all + |from Standard.Base.Data.Numbers import Number | |main = | x = 6 @@ -162,7 +145,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idMainX, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -179,11 +162,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" ) ), @@ -202,7 +185,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idMainZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -219,7 +202,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idFooY, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -236,7 +219,7 @@ class RuntimeVisualisationsTest Set( Api.ExpressionUpdate( Main.idFooZ, - Some(Constants.INTEGER), + Some(ConstantsGen.INTEGER), None, Vector(Api.ProfilingInfo.ExecutionTime(0)), fromCache, @@ -268,7 +251,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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -309,12 +292,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -324,7 +307,7 @@ class RuntimeVisualisationsTest requestId, Api.AttachVisualisation( visualisationId, - idMain, + idMainRes, Api.VisualisationConfiguration( contextId, "Enso_Test.Test.Visualisation", @@ -333,7 +316,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) @@ -345,7 +328,7 @@ class RuntimeVisualisationsTest Api.VisualisationContext( `visualisationId`, `contextId`, - `idMain` + `idMainRes` ), data ) @@ -359,7 +342,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) @@ -371,7 +354,7 @@ class RuntimeVisualisationsTest Api.VisualisationContext( `visualisationId`, `contextId`, - `idMain` + `idMainRes` ), data ) @@ -422,7 +405,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -445,7 +428,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -470,7 +453,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) ) @@ -487,7 +470,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) @@ -551,7 +534,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -574,7 +557,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -610,7 +593,7 @@ class RuntimeVisualisationsTest ) ) - val editFileResponse = context.receive(2) + val editFileResponse = context.receiveN(2) editFileResponse should contain( context.executionComplete(contextId) ) @@ -673,7 +656,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -696,7 +679,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -732,7 +715,7 @@ class RuntimeVisualisationsTest ) ) - val editFileResponse = context.receive(2) + val editFileResponse = context.receiveN(2) editFileResponse should contain( context.executionComplete(contextId) ) @@ -793,7 +776,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -817,7 +800,7 @@ class RuntimeVisualisationsTest ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -852,7 +835,7 @@ class RuntimeVisualisationsTest ) ) ) - val modifyVisualisationResponses = context.receive(2) + val modifyVisualisationResponses = context.receiveN(2) modifyVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationModified()) ) @@ -919,7 +902,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( @@ -939,7 +922,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - val pushResponses = context.receive(6) + val pushResponses = context.receiveNIgnoreStdLib(6) pushResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), context.Main.Update.mainX(contextId), @@ -984,7 +967,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) ) @@ -1001,7 +984,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) ) @@ -1049,7 +1032,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -1072,7 +1055,7 @@ class RuntimeVisualisationsTest ) ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -1108,7 +1091,7 @@ class RuntimeVisualisationsTest ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( context.executionComplete(contextId) ) } @@ -1153,7 +1136,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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), @@ -1177,7 +1160,7 @@ class RuntimeVisualisationsTest ) ) - val attachVisualisationResponses = context.receive(2) + val attachVisualisationResponses = context.receiveN(2) attachVisualisationResponses should contain( Api.Response(requestId, Api.VisualisationAttached()) ) @@ -1223,7 +1206,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()) @@ -1247,7 +1230,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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1277,12 +1260,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1301,13 +1284,13 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response(requestId, Api.ModuleNotFound("Test.Undefined")) ) } 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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1337,12 +1320,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1363,7 +1346,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) @@ -1395,7 +1378,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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1425,12 +1408,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1449,7 +1432,7 @@ class RuntimeVisualisationsTest ) ) ) - context.receive(1) should contain theSameElementsAs Seq( + context.receiveN(1) should contain theSameElementsAs Seq( Api.Response( requestId, Api.VisualisationExpressionFailed( @@ -1469,7 +1452,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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1499,12 +1482,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1523,7 +1506,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( @@ -1556,7 +1539,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(99, 1) val contents = context.Main.code val mainFile = context.writeMain(context.Main.code) val moduleName = "Enso_Test.Test.Main" @@ -1604,12 +1587,12 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(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, idMain, ConstantsGen.INTEGER), context.executionComplete(contextId) ) @@ -1628,7 +1611,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( @@ -1675,10 +1658,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 +1690,9 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(3) should contain theSameElementsAs Seq( + val responses = context.receiveN(n = 4, timeoutSeconds = 60) + + responses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( contextId, @@ -1717,6 +1702,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( @@ -1732,7 +1723,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) @@ -1761,10 +1752,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 @@ -1793,7 +1784,7 @@ class RuntimeVisualisationsTest context.send( Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) - context.receive(3) should contain theSameElementsAs Seq( + context.receiveNIgnoreStdLib(3) should contain theSameElementsAs Seq( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.panic( contextId, @@ -1818,7 +1809,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, @@ -1863,11 +1854,11 @@ class RuntimeVisualisationsTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(77, 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 = | Error.throw List.Empty_Error @@ -1902,7 +1893,7 @@ class RuntimeVisualisationsTest Api.Request(requestId, Api.PushContextRequest(contextId, item1)) ) val pushContextResponses = - context.receive(n = 4, timeoutSeconds = 90) + context.receiveN(n = 5, timeoutSeconds = 90) pushContextResponses should contain allOf ( Api.Response(requestId, Api.PushContextResponse(contextId)), TestMessages.error( @@ -1933,7 +1924,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) 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/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..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.Builtins import all + """from Standard.Base.Data.List import Cons | |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(49, 36, classOf[ApplicationNode]) + instrumenter.assertNodeExists(74, 8, classOf[ApplicationNode]) eval(code) () } @@ -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) () } @@ -88,7 +88,8 @@ class CodeLocationsTest extends InterpreterTest { withLocationsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |import Standard.Base.Nothing + |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(137, 5, classOf[ApplicationNode]) + instrumenter.assertNodeExists(155, 1, classOf[ReadLocalVariableNode]) + instrumenter.assertNodeExists(151, 7, classOf[ApplicationNode]) + instrumenter.assertNodeExists(163, 9, classOf[ApplicationNode]) eval(code) () } @@ -112,7 +113,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 +130,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 +266,7 @@ class CodeLocationsTest extends InterpreterTest { instrumenter => val code = """ - |from Standard.Builtins import all + |from Standard.Base.Data.List import all | |type MyAtom | @@ -276,9 +277,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/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index d4d3f968dc5b..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 @@ -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,7 @@ 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 | |main = | x = Panic.catch_primitive @ caught_panic-> caught_panic.payload @@ -36,20 +36,20 @@ 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 | |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 | |foo = | my_var = 10 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/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index 307150a5f9a1..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 @@ -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 @@ -85,7 +85,8 @@ 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 deaa966d0672..3f3d0ae050ff 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 @@ -65,7 +65,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 cc49c3b55b36..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 @@ -11,7 +11,9 @@ 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 | |type MyError | @@ -29,7 +31,9 @@ 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 | |type MyError | @@ -48,7 +52,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 @@ -59,7 +63,9 @@ 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 | |type MyCons err | @@ -73,7 +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 + |import Standard.Base.IO | |type MyRecovered x |type MyError x @@ -96,7 +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 + |import Standard.Base.IO | |type My_Atom a |type My_Error @@ -113,7 +121,8 @@ 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 |type My_Error @@ -132,7 +141,8 @@ 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 | @@ -148,7 +158,8 @@ 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 | @@ -163,7 +174,8 @@ 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 | @@ -175,5 +187,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/DateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DateTest.scala index 8d72279b2e91..2226a51b032e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/DateTest.scala @@ -10,7 +10,7 @@ class DateTest extends InterpreterTest { ): Unit = { "evaluate a date expression" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO | |import Standard.Base.Data.Time.Date | @@ -23,7 +23,7 @@ class DateTest extends InterpreterTest { "print out java date" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO |polyglot java import java.time.LocalDate | |main = @@ -35,7 +35,7 @@ class DateTest extends InterpreterTest { "send enso date into java" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO |polyglot java import java.time.LocalTime |import Standard.Base.Data.Time.Date | @@ -52,7 +52,7 @@ class DateTest extends InterpreterTest { "check java date has enso methods" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO |polyglot java import java.time.LocalDate |import Standard.Base.Data.Time.Date | @@ -73,7 +73,7 @@ class DateTest extends InterpreterTest { "check enso date has enso methods" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO |import Standard.Base.Data.Time.Date | |main = 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..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,8 @@ 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 = | Debug.eval $rawTQ @@ -23,7 +24,8 @@ 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 = | x = "Hello World!" @@ -36,7 +38,8 @@ 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 | @@ -51,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 @@ -65,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 -> @@ -79,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/ExpressionIdTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala index 4d3bc21a6c8c..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 @@ -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") @@ -55,7 +55,8 @@ class ExpressionIdTest extends InterpreterTest { withIdsInstrumenter { instrumenter => val code = """ - |from Standard.Builtins import all + |import Standard.Base.Nothing + |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(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") @@ -83,7 +84,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 +102,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/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/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/InteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/InteropTest.scala index 7b9657b2a1cf..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 @@ -44,9 +44,9 @@ 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 + |Any.Any.method = this | |main = x -> .method |""".stripMargin @@ -57,10 +57,11 @@ class InteropTest extends InterpreterTest { "work with unresolved symbols" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers import all + |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/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/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/LambdaShorthandArgsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala index 45c32a4303f7..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.Builtins import all + """from Standard.Base.Data.Numbers import all | |Number.if_then_else = ~t -> ~f -> if this == 0 then t else f | @@ -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 @@ -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.Numbers 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 a51c5da14b34..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 @@ -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 @@ -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 | @@ -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 -> @@ -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.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/MethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MethodsTest.scala index 733f6e997d32..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 @@ -24,9 +24,10 @@ class MethodsTest extends InterpreterTest { "execute `this` argument once" in { val code = - """from Standard.Builtins import all + """from Standard.Base.IO import all + |import Standard.Base.Nothing | - |Nothing.foo = 0 + |Nothing.Nothing.foo = 0 | |main = (IO.println "foo").foo |""".stripMargin @@ -87,9 +88,9 @@ 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 = + |Any.Any.method = | x = this * this | y = x * 2 | y + 1 @@ -101,7 +102,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 @@ -125,13 +126,15 @@ 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 + |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 @@ -149,9 +152,23 @@ 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.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/NamedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala index 07cb775a14e4..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 @@ -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/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/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/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/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index 549780ff144f..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 @@ -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" @@ -56,5 +56,73 @@ class PolyglotTest extends InterpreterTest { "callFunctionAndIncrement" ) } + + "match on Polyglot type when imported everything from stdlib" in { + val code = + """from Standard.Base import all + |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.Base.IO import all + |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 only importing Polyglot module" in { + val code = + """import Standard.Base.Polyglot + |from Standard.Base.IO import all + |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.Base.IO import all + |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/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..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,9 @@ 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 | |foo x = | if x == 0 then IO.println "Start." else Nothing @@ -75,7 +77,8 @@ 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 | @@ -113,7 +116,9 @@ 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 | |type Mock_File i | @@ -152,7 +157,9 @@ 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 | |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 af8cfad6d5bf..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 @@ -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.Base.Data.Numbers 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.Base.Data.Numbers 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.Base.Data.Numbers import Number | |main = | stateSum = n -> @@ -64,7 +67,11 @@ class StateTest extends InterpreterTest { "work with pattern matches" in { val code = - """from Standard.Builtins import all + """from Standard.Base.Data.Numbers 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 @@ -90,7 +97,8 @@ class StateTest extends InterpreterTest { "undo changes on Panics" in { val code = - """from Standard.Builtins import all + """from Standard.Base import all + |import Standard.Base.Runtime.State | |panicker = | State.put Number 400 @@ -108,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.Base.Data.Numbers import Number | |inner = State.put Number 0 | @@ -124,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 @@ -146,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/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/SystemProcessTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SystemProcessTest.scala index e39a8eddff8b..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 @@ -18,7 +18,9 @@ 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 | |main = | result = System.create_process "echo" Array.empty "" False False False @@ -31,7 +33,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_1 "/c") "" False False False @@ -44,7 +48,9 @@ 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 |""".stripMargin @@ -56,7 +62,9 @@ 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 | |main = | result = System.create_process "ls" (Array.new_1 "--gibberish") "" False False False @@ -70,7 +78,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "exit 7") "" False False False @@ -84,7 +94,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; echo $line") "" True True True @@ -99,7 +111,9 @@ 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 | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "" True True True @@ -115,7 +129,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "wc -c") "" True True True @@ -130,7 +146,9 @@ 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 | |main = | result = System.create_process "echo" (Array.new_1 "42") "" True True True @@ -145,7 +163,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -160,7 +180,9 @@ 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 | |main = | result = System.create_process "echo" (Array.new_1 "9") "" True True True @@ -174,7 +196,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo 9") "" True True True @@ -188,7 +212,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "read line; printf $line") "hello" False False False @@ -202,7 +228,9 @@ 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 | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::ReadLine()") "hello" False False False @@ -216,7 +244,9 @@ 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 | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False True True @@ -230,7 +260,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False True True @@ -244,7 +276,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\x01\x0F\x10'") "" False True True @@ -258,7 +292,9 @@ 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 | |main = | result = System.create_process "echo" (Array.new_1 "foobar") "" False False False @@ -273,7 +309,9 @@ 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 | |main = | result = System.create_process "cmd" (Array.new_2 "/c" "echo foobar") "" False False False @@ -288,7 +326,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False True True @@ -302,7 +342,9 @@ 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 | |main = | result = System.create_process "PowerShell" (Array.new_2 "-Command" "[System.Console]::Error.WriteLine('err')") "" False True True @@ -316,7 +358,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf '%b' '\xCA\xFE\xBA\xBE' 1>&2") "" False True True @@ -330,7 +374,9 @@ 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 | |main = | result = System.create_process "bash" (Array.new_2 "-c" "printf err 1>&2") "" False False False @@ -344,7 +390,9 @@ 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 | |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/interpreter/test/semantic/TextTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/TextTest.scala index f88fdfcaad19..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 @@ -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 @@ -67,7 +67,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 @@ -78,7 +78,7 @@ class TextTest extends InterpreterTest { "support printing to standard error" in { val code = - s"""from Standard.Builtins import all + s"""import Standard.Base.IO | |main = IO.print_err "My error string" |""".stripMargin @@ -91,7 +91,7 @@ class TextTest extends InterpreterTest { val inputString = "foobarbaz" val code = - """from Standard.Builtins import all + """import Standard.Base.IO | |main = | IO.readln + " yay!" @@ -105,7 +105,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 + |import Standard.Base.Data.Text + |import Standard.Base.IO + |import Standard.Base.Nothing | |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 71f9058381f6..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 @@ -11,7 +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.IO import all | |main = | if True then IO.println "true when true" else IO.println "false when true" @@ -23,9 +24,10 @@ 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.IO import all | - |Boolean.isTrue = this + |Boolean.Boolean.isTrue = this | |main = | true = 1 == 1 @@ -39,7 +41,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 @@ -54,7 +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 | |True.to_num = 1 |False.to_num = 2 @@ -66,9 +68,9 @@ 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 + |Boolean.Boolean.to_num = 2 |True.to_num = 1 | |main = True.to_num + False.to_num @@ -78,7 +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.IO import all | |main = | IO.println True&&False @@ -93,7 +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.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 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/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java new file mode 100644 index 000000000000..3b8225421e29 --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -0,0 +1,22 @@ +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 { + + /** Fully qualified name as available in stdlib */ + String name() default ""; + + /** + * Comma-separated list of parameters of builting type + * + * @return list of params + */ + 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 new file mode 100644 index 000000000000..7949df8eb76f --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsMetadataProcessor.java @@ -0,0 +1,124 @@ +package org.enso.interpreter.dsl; + +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.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.NoSuchFileException; +import java.util.*; +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 { + + /** + * 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()) { + 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 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()); + 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) { + // This is the first time we are generating the metadata file, ignore the exception. + 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); + // Dump past entries, to workaround separate compilation + annotation processing issues + 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); + } + } + + /** + * 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} + * @return as in {@link #process} + */ + 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 ce75e5e55eb6..24a74aa01db4 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 @@ -12,25 +12,33 @@ import javax.tools.JavaFileObject; import java.io.IOException; import java.io.PrintWriter; +import java.io.Writer; import java.util.*; import java.util.stream.Collectors; import org.openide.util.lookup.ServiceProvider; -/** 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) @ServiceProvider(service = Processor.class) -public class MethodProcessor extends AbstractProcessor { +public class MethodProcessor extends BuiltinsMetadataProcessor { + + private final Map> builtinMethods = new HashMap<>(); /** - * Processes annotated elements, generating code for each of them. + * 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. * @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) { @@ -55,12 +63,26 @@ 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); + 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); + if (def.hasAliases()) { + for (String alias : def.aliases()) { + registerBuiltinMethod(processingEnv.getFiler(), alias, fullClassName); + } + } + } catch (IOException e) { e.printStackTrace(); } @@ -391,6 +413,47 @@ 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) { + 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..3e663117af66 --- /dev/null +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -0,0 +1,169 @@ +package org.enso.interpreter.dsl; + +import javax.annotation.processing.*; +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.*; + +import org.apache.commons.lang3.StringUtils; +import org.openide.util.lookup.ServiceProvider; + +@SupportedAnnotationTypes("org.enso.interpreter.dsl.BuiltinType") +@SupportedSourceVersion(SourceVersion.RELEASE_11) +@ServiceProvider(service = Processor.class) +public class TypeProcessor extends BuiltinsMetadataProcessor { + private final Map> builtinTypes = new HashMap<>(); + + private class BuiltinTypeConstr { + private String tpeName; + private String fullName; + private String[] paramNames; + + 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; + } + + 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 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.name(), + 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 { + 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( + entry.getKey() + + ":" + + constr.getTpeName() + + ":" + + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") + + ":" + + constr.getFullName() + + "\n"); + if (pastEntries.containsKey(entry.getKey())) { + pastEntries.remove(entry.getKey()); + } + } + } + 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[3].isEmpty()) { + out.println( + " public static void final String " + + elements[0].toUpperCase() + + " = \"" + + elements[3] + + "\";"); + } + }); + + out.println(); + out.println("}"); + } + } + + 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, fullName, params)); + } + + @Override + protected String metadataPath() { + return META_PATH; + } + + @Override + 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; +} 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..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 @@ -12,6 +12,9 @@ /** 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('.', '/') + "/BuiltinMethods.metadata"; private final String packageName; private final String originalClassName; @@ -48,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 < methodNames.length; i++) { + methodNames[i] = annotation.type() + "." + methodNames[i]; + } + return methodNames; + } + } + private String initConstructor(TypeElement element) { boolean useBuild = element.getEnclosedElements().stream() @@ -138,6 +157,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(); 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/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/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 = diff --git a/test/Tests/src/Data/Array_Spec.enso b/test/Tests/src/Data/Array_Spec.enso index 5effdecd8b83..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 @@ -26,3 +28,9 @@ 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 + + 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 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/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" <| diff --git a/test/Tests/src/Data/Numbers_Spec.enso b/test/Tests/src/Data/Numbers_Spec.enso index ba5164721aef..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.Extensions import Parse_Error +from Standard.Base.Data.Numbers import Parse_Error import Standard.Test 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 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/Case_Spec.enso b/test/Tests/src/Semantic/Case_Spec.enso index d70c01ca5bf6..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.Test polyglot java import java.util.Random @@ -88,3 +87,5 @@ spec = Test.group "Pattern Matches" <| 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 24644db5d1a0..a12aba76a313 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -import Standard.Base.System.Platform from Standard.Base.Data.Text.Text_Sub_Range import Last +import Standard.Base.System.Platform import Standard.Test @@ -87,9 +87,11 @@ 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.Builtins.Main.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" <| Enso_Project.name.should_equal 'Tests' Base.enso_project.name.should_equal 'Base' + +main = Test.Suite.run_main here.spec 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 + 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 diff --git a/test/Visualization_Tests/src/Sql_Spec.enso b/test/Visualization_Tests/src/Sql_Spec.enso index d8b50ecaa531..05acc12c16b6 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.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]]] 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."